Maximum flow
how it works
Places keep their letters from the watch page's grid, A to D above and E to H below, so a map can skip a letter. On the watch page's map, a road's number is the room left on it. The number next to the source and the sink is what has been sent so far.
Maximum flow finds the most that can be sent from one place, the source, to another, the sink, along one-way roads that each have a limit. Search outward, nearest places first, for a way from source to sink with room at every step. Each place tries its neighbours in letter order. Send as much as the way's tightest step allows, then search again. A step usually goes forwards along a road with room. It may also go backwards along a road with something sent, which takes some of that back. When no way is left, what was sent is the most there is, and the places the source can still reach mark the narrowest cut, as question 4 shows. Nothing moves backwards on the map: taking back only sends the same amount by another road. This page counts the looks and the ways. A look goes from a place the search has reached to one it has not, whether or not it finds room. A road looked along in two searches counts twice. Where the code says sort, that only keeps letter order.
| search | way it finds | room at its tightest step | sent in all | looks |
|---|---|---|---|---|
| 1 | A, B, F, G | 3 | 3 | 6 |
| 2 | A, E, F, B, C, D, G | 2 | 5 | 8 |
| 3 | none | 5 | 6 |
step 1 of 7
Send as much as possible from A to H. Nothing is sent yet, so every road has all its room.
what it remembers to know where it is
- way found
- not yet
- sent so far
- 0
Where it says not yet, nothing is held there at that moment.
step 2 of 7
The shortest way with room on every road is A, B, G and H. Its tightest road has room for 99.
what it remembers to know where it is
- way found
- ABGH
- sent so far
- 0
step 3 of 7
Send 99 along A, B, G and H: each road on the way has that much less room, or gets that much back. 99 sent in all.
what it remembers to know where it is
- way found
- ABGH
- sent so far
- 99
step 4 of 7
The shortest way with room is A, F, G, B, C, D and H. It travels the road from B to G backwards, taking back some of what was sent along it. Its tightest step has room for 99.
what it remembers to know where it is
- way found
- AFGBCDH
- sent so far
- 99
step 5 of 7
Send 99 along A, F, G, B, C, D and H: each road on the way has that much less room, or gets that much back. 198 sent in all.
what it remembers to know where it is
- way found
- AFGBCDH
- sent so far
- 198
step 7 of 7
No way with room is left, so 198 is the most that can be sent. The places the source can still reach, A, E and F, are on one side of the narrowest cut.
what it remembers to know where it is
- way found
- not yet
- sent so far
- 198
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- nothing sent yet: every road has all its roomPython lines 11, 12, 13, 14, 15, 16, 17, 18, 19 and 20
- find the shortest way from the source to the sink with room on every roadPython lines 21, 22, 23, 24, 25, 26, 27, 28, 29, 33, 34 and 35
- a road travelled backwards has as much room as was sent along itPython lines 15 and 40
- send as much as the tightest road on the way allows, and repeatPython lines 36, 37, 38, 39, 40 and 41
- no way with room left: nothing more can be sentPython line 30
- the places the source can still reach are one side of the narrowest cutPython lines 31 and 32
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from collections import deque
def maximum_flow(roads, source, sink):
"""Find the most that can be sent from source to sink.
roads is a list of (from, to, limit), each running one way, at most one
between two places, each limit at least 1. Returns what is written at the
two ends: how much left source and how much reached sink, one number.
"""
room = {} # what can still go from one place straight to another
near = {} # each place's neighbours, along a road running either way
for a, b, limit in roads:
room[a, b] = limit # nothing sent yet: all its room
room[b, a] = 0 # backwards, nothing sent yet to take back
near.setdefault(a, []).append(b)
near.setdefault(b, []).append(a)
for names in near.values():
names.sort() # letter order
total = 0
while True:
came_from = {source: source} # search, nearest places first
queue = deque([source])
while queue and sink not in came_from:
here = queue.popleft()
for there in near[here]:
if there not in came_from and room[here, there] > 0:
came_from[there] = here # a step with room
queue.append(there)
if sink not in came_from: # no way with room left
# came_from holds what source can still reach: one side of the narrowest cut
return {source: total, sink: total}
way = [sink]
while way[-1] != source: # walk back along the way found
way.append(came_from[way[-1]])
steps = list(zip(way[1:], way))
amount = min(room[step] for step in steps) # its tightest step
for here, there in steps:
room[here, there] -= amount # that much less room this way
room[there, here] += amount # and that much more the other way
total += amount
how it scales
The plot counts the looks on two maps of places, every limit 1, measured from 10 to 1,000 places. One is a line, from the first place to the last. The other is a fan: the source has a road to each place between, and each of those a road to the sink.
Each mark across or up is ten times the one before. The line climbs one mark up for each mark across: 100 at 100 places and 1,000 at 1,000, 10 times. The fan climbs two: 9,800 at 100 places and 998,000 at 1,000, about 102 times, near 10 times 10. A slope of 1 means it grows as , and a slope of 2 as , as section 4's questions 1 and 2 derive.
roads looked along, ten times more at each mark up
, n, ten times more at each mark to the right
- a fan, every limit 1solid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
- a line, every limit 1solid where measured by running it; dashed where its formula carries it on to ten million
| roads looked along | time | |
|---|---|---|
| 1,000 | 998,000 | about 998 microseconds |
| 100,000 | 9,999,800,000 | about 10 seconds |
| 10,000,000 | 99,999,980,000,000 | about 1.2 days |
The roads looked along are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count maximum flow's looks yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it runs two maps of n places,
every limit 1: a line from the first place to the last, and a fan, the source
with a road to each place between and each of those with a road to the sink. It
prints the looks on each. The counts are the same on any computer; only the time
differs.
"""
from collections import deque
def maximum_flow(roads, source, sink):
"""Find the most that can be sent from source to sink.
roads is a list of (from, to, limit), each running one way, at most one
between two places, each limit at least 1. Returns what is written at the
two ends: how much left source and how much reached sink, one number.
"""
room = {} # what can still go from one place straight to another
near = {} # each place's neighbours, along a road running either way
for a, b, limit in roads:
room[a, b] = limit # nothing sent yet: all its room
room[b, a] = 0 # backwards, nothing sent yet to take back
near.setdefault(a, []).append(b)
near.setdefault(b, []).append(a)
for names in near.values():
names.sort() # letter order
total = 0
while True:
came_from = {source: source} # search, nearest places first
queue = deque([source])
while queue and sink not in came_from:
here = queue.popleft()
for there in near[here]:
if there not in came_from and room[here, there] > 0:
came_from[there] = here # a step with room
queue.append(there)
if sink not in came_from: # no way with room left
# came_from holds what source can still reach: one side of the narrowest cut
return {source: total, sink: total}
way = [sink]
while way[-1] != source: # walk back along the way found
way.append(came_from[way[-1]])
steps = list(zip(way[1:], way))
amount = min(room[step] for step in steps) # its tightest step
for here, there in steps:
room[here, there] -= amount # that much less room this way
room[there, here] += amount # and that much more the other way
total += amount
def count(roads, source, sink):
"""The looks the run makes: the same run, with a count added.
A look goes from a place the search has reached to one it has not, and it
counts whether or not it finds room.
"""
room = {}
near = {}
for a, b, limit in roads:
room[a, b] = limit
room[b, a] = 0
near.setdefault(a, []).append(b)
near.setdefault(b, []).append(a)
for names in near.values():
names.sort()
looks = 0
while True:
came_from = {source: source}
queue = deque([source])
while queue and sink not in came_from:
here = queue.popleft()
for there in near[here]:
if there in came_from:
continue
looks += 1
if room[here, there] > 0:
came_from[there] = here
queue.append(there)
if sink not in came_from:
return looks
way = [sink]
while way[-1] != source:
way.append(came_from[way[-1]])
steps = list(zip(way[1:], way))
amount = min(room[step] for step in steps)
for here, there in steps:
room[here, there] -= amount
room[there, here] += amount
def names(n):
"""n names that sort in the order they count."""
return [f"p{k:04}" for k in range(1, n + 1)]
def line(n):
"""Places one after another in letter order, each limit 1."""
places = names(n)
return [(places[k], places[k + 1], 1) for k in range(n - 1)], places[0], places[-1]
def fan(n):
"""The source, a road to each place between, and a road from each to the sink, each limit 1."""
places = names(n)
source, sink = places[0], places[-1]
return [road for p in places[1:-1] for road in ((source, p, 1), (p, sink, 1))], source, sink
if __name__ == "__main__":
print(f"{'n':>6} {'line':>8} {'fan':>8} {'n(n - 2)':>10}")
for n in [10, 100, 1000]:
print(f"{n:>6} {count(*line(n)):>8} {count(*fan(n)):>8} {n * (n - 2):>10}")
best, worst and average
Here best and worst only name two maps. Best is a line, with one way to send along, and worst is a fan, with one for each place between. The table below has a map cheaper than both and a map dearer than both. On any map the ceiling is , from question 6. No average is worked out, as there is no one way to pick a map.
A case is one kind of map, such as a fan. A bound says how fast that case's cost grows as places are added.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| besta line, every limit 1 | worsta fan, every limit 1 | |
|---|---|---|
| roads looked along | , from 2 places on | , from 3 places on |
| ways sent along | 1 | , from 3 places on |
| how the roads looked along grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: Two numbers and two names for each road, and at most places each in the queue, the note of where each place came from, and the way.
Extra memory is the room it needs on top of the input itself, while it runs.
| map | places | roads | ways | looks |
|---|---|---|---|---|
| a line of 4 | 4 | 3 | 1 | 4 |
| a fan of 4 | 4 | 4 | 2 | 8 |
| cheaper than both | 4 | 2 | 0 | 1 |
| dearer than both | 4 | 5 | 3 | 17 |
| the small map | 7 | 8 | 2 | 20 |
where the formula comes from
Questions 1 and 2 are the counts the plot draws.
the move: the first search
the line:A line of 4, from A to D. search looks along looks 1 A to B, B to C, C to D 3 2 A to B, now full 1 Search by search. why it is allowed: Each place it reaches has one road onward. The road behind leads to a place already reached, so it gets no look. For 4 places, 3.
the move: the last search
the line:why it is allowed: The one way sends 1, which fills every road. So the first road has no room, the source has no other, and the search ends there.
guess it, thenthe move: add them
the line:why it is allowed: Lines 1 and 2, and 1. For 4 places, 3 + 1, which is 4.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 3 says they are equal, so this holds.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: Line 3 again, the other way round.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth. means both.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the ways
the line:search looks from A looks from the next place way it finds 1 2 1 A, B, F 2 2 1 A, E, F 3 2 0 none The fan of 4. Search 2 still looks along A to B, now full. In all, 3 + 3 + 2, which is 8. why it is allowed: Each way sends 1, which fills its two roads, so no place between is on a second way. While one still has room, a search finds it. For 4 places, 2.
the move: a search that finds one
the line:why it is allowed: The source looks along all its roads, full or not. Then the first place between with room looks along its road to the sink, and the search ends.
guess it, thenthe move: the last search
the line:why it is allowed: Every road from the source is full now, so the search reaches nothing more.
guess it, thenthe move: add them
the line:why it is allowed: Lines 1 to 3, a search for each way and the last one. For 4 places, 2 times 3 plus 2, which is 8.
guess it, thenthe move: take out n - 2
the line:why it is allowed: Both parts hold , once times and once more, so times in all.
guess it, thenthe move: a ceiling
the line:why it is allowed: is below . For 4 places, is 8, at most 16.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: From 4 places on, is at least half of . For 4 places, is 8, at least 8.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 8, with the fixed multiple a half.
guess it, thenthe move: both together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, only a fixed multiple apart.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: one road, two steps
the line:road B to F room forwards room backwards at the start 3 0 after way 1 0 3 after way 2 2 1 On the small map. Its limit is 3, and the two columns add up to 3 in every row. why it is allowed: Together they always add up to the road's limit. Sending along one takes from it and adds to the other.
the move: within its limit
the line:why it is allowed: A way sends no more than its tightest step's room. So a forwards step cannot pass the limit, and a backwards step cannot take back more than was sent.
guess it, thenthe move: each place stays even
the line:step in step out takes in sends on forwards forwards k more k more forwards backwards k more and k less same backwards forwards same k less and k more backwards backwards k less k less Here k is the amount the way sends. Way 2 reaches F forwards and leaves it backwards, so F takes 2 more from E and 2 less from B, and still sends 3 to G. why it is allowed: A way meets a place once, with one step in and one step out. Whichever way each step points, the place's takings and sendings stay level, as the table shows.
guess it, thenthe move: more arrives
the line:why it is allowed: A way leaves the source once and never returns, and it reaches the sink once and stops there. So what left and what arrived stay one number.
guess it, thenthe move: so no rule breaks
the line:why it is allowed: Lines 2 to 4 are the rules, and each way keeps them.
guess it, thenthe move: how many steps
the line:why it is allowed: Line 1 gives each road two steps, with room or not, so roads give . A line has roads. For 4 places, 6.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: a cut
the line:source's side roads leaving it road running back size A A to B 3, A to E 4 none 7 A, E A to B 3, E to F 3 none 6 A, E, F A to B 3, F to G 3 B to F 6 A, B, E, F B to C 2, F to G 3 none 5 Four of the small map's cuts. 5 is the smallest of them all. why it is allowed: A cut's size is the limits of the roads from the source's side to the sink's side, added up. Roads running the other way do not count.
the move: add up over the side
the line:side A, B, F leaves arrives leaves less arrives A 5 0 5 B 3 3 0 F 3 3 0 in all 11 6 5 The small map at the end. A sent 5. why it is allowed: A sending is any amounts on the roads, each within its limit, each place between sending on all it takes in. Question 3 shows the run's is one. So the sum is what the source sent.
guess it, thenthe move: only the crossing roads
the line:why it is allowed: A road inside the side counts once leaving and once arriving, so it cancels. Here A to B's 3 and B to F's 1 cancel. A to E 2, B to C 2 and F to G 3 cross out, 7 in all, and E to F's 2 crosses back. 7 less 2 is 5.
guess it, thenthe move: any cut is a ceiling
the line:why it is allowed: What crosses back is at least 0. What crosses out is at most the limits of those roads, which is the size. Here 5 is at most 7, and 7 at most the size, 9.
guess it, thenthe move: where the run stops
the line:The small map at the end, each number what was sent. A reaches E, F, then B by taking back 1 of what B sent to F. B to C and F to G leave the shade, at their limits. why it is allowed: No way is left, so the sink is not among those places. So this is a cut.
guess it, thenthe move: each road out is full
the line:why it is allowed: If it had room, a step along it would reach its far end, which would then be on the side.
guess it, thenthe move: each road in is empty
the line:why it is allowed: If something had been, a step backwards would reach its start, which would then be on the side. On the small map, no road enters the side.
guess it, thenthe move: so they meet
the line:why it is allowed: In line 3, what crosses out is the whole size, by line 6, and what crosses back is 0, by line 7. On the small map, 2 + 3, which is 5.
guess it, thenthe move: nothing sends more
the line:why it is allowed: By line 4 no sending passes this cut's size, and by line 8 the run sends all of it.
guess it, thenthe move: no cut is smaller
the line:why it is allowed: By line 4 every cut is at least what was sent, and by line 8 this cut is just that. Books call this the max-flow min-cut theorem.
guess it, thenthe move: on a fan
the line:why it is allowed: By line 10 the run's last side is the narrowest cut. On a fan the source's roads are all full at the end, so that side is the source alone, with roads of limit 1. For 4 places, 2.
guess it, then
try it with a small : at , line 11 gives , which you can work out by hand
the move: hops
the line:hops to before way 1 after way 1 A 0 0 B 1 3 C 2 4 D 3 5 E 1 1 F 2 2 G 3 6 On the small map. No place's hops go down, and the sink goes from 3 hops to 6. why it is allowed: A place's hops are the fewest steps with room from the source to it. The search goes nearest first, so it finds a way of fewest steps. Each place on it has as many hops as steps taken to reach it, as a shorter route to it would make the whole way shorter. Way 1, A, B, F, G, reads 0, 1, 2, 3.
the move: a new step
the line:why it is allowed: A step can gain room only if the way travelled it the other way round. By line 1, that one went one hop further, so the new one goes one hop back.
guess it, thenthe move: suppose one falls
the line:why it is allowed: Compare hops before a way is sent with hops after it. Suppose some places fall. Of those, take y, with the fewest hops after. Let x come just before y on a route of fewest steps after. x has one hop less than y, so x did not fall.
guess it, thenthe move: no place falls
the line:step x to y x after y after x before y before had room before 2 3 at most 2 at most 3 is new 2 3 at most 2 at most 1 Say y has 3 hops after, so x has 2. In both rows y before is at most 3, so y did not fall. why it is allowed: Before, x had at most its hops after. If x to y had room before, y before had at most one more than x before. If x to y is new, y before had one less than x before, by line 2. Either way y did not fall, yet line 3 chose y as one that fell. So no place can fall.
guess it, thenthe move: tightest twice
the line:why it is allowed: The tightest step, x to y, has no room left, with y one hop past x. It gets room again only when a way travels y to x, and then x is one hop past y. By line 4, y has not fallen, so x has risen by at least 2. On the small map, way 1 fills B to F with B at 1 hop, and way 2 travels F to B with B at 3.
guess it, thenthe move: how many times
the line:why it is allowed: A way meets no place twice, so a step's end has at most hops and its start at most . Rising by at least 2 each time from 0 or more, that fits half of times at most. For 4 places, a start has 0, 1 or 2 hops, which fits 2 times at most.
guess it, thenthe move: every way has one
the line:why it is allowed: Each way has a tightest step, and question 3 gives steps. So there are at most times half of ways, which is . On the small map, 7 times 8, which is 56, against the 2 it takes.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: one search
the line:the small map's search looks roads 1 6 8 2 8 8 3 6 8 No search looks along more than its 8 roads. why it is allowed: A look goes from a place the search has reached to one it has not, and the search leaves each place once. Take a road from B to F. The end the search leaves first looks along the road only if the other end is not yet reached. When the search leaves that other end, the first is already reached, so there is no second look.
the move: every search
the line:why it is allowed: Question 5's ways, and one last search that finds none. For the small map, 57.
guess it, thenthe move: their looks
the line:why it is allowed: Line 1 gives at most looks a search. For the small map, 57 times 8, which is 456, and the run makes 20.
guess it, thenthe move: on a fan
the line:why it is allowed: A fan has roads, put in for . For 4 places, 17 times 4, which is 68, and question 2 counts 8.
guess it, thenthe move: the rest of one search
the line:why it is allowed: A road is on two places' lists, so a search reads at most names. A way walks back and sends along at most steps. A road has 2 ends and every place is on a road, so is at most .
guess it, thenthe move: all of it
the line:why it is allowed: Lines 2, 3 and 5. For the small map, 448 + 8, which is 456.
guess it, thenthe move: read the bound
the line:why it is allowed: is at most , so all of it is at most a fixed multiple of . Reading the roads is a fixed multiple of . Sorting the lists, names in all, compares each name with at most every other, so a fixed multiple of . Neither grows faster than . A computer does each look or send in a fixed few actions.
guess it, thenthe move: in books
the line:why it is allowed: In books is the places and the roads.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
A fan of 4, every limit 1. The watch page writes this map as A>B 1, A>E 1, B>F 1, E>F 1; A F. A>B 1 means a road from A to B with a limit of 1, and after the semicolon come the source and the sink. Each way takes two rows of the table, one finding it and one sending. It is counted when found. Only a search adds looks, the last one too, though it finds none.
| step | what happens | ways sent along | roads looked along |
|---|---|---|---|
| 1 | Send as much as possible from A to F. Nothing is sent yet, so every road has all its room. | 0 | 0 |
| 2 | The shortest way with room on every road is A, B and F. Its tightest road has room for 1. | 1 | 3 |
| 3 | Send 1 along A, B and F: each road on the way has that much less room, or gets that much back. 1 sent in all. | 1 | 3 |
| 4 | The shortest way with room on every road is A, E and F. Its tightest road has room for 1. | 2 | 6 |
| 5 | Send 1 along A, E and F: each road on the way has that much less room, or gets that much back. 2 sent in all. | 2 | 6 |
| 6 | Search once more for a way from A to F with room on every road. There is none. | 2 | 8 |
| 7 | No way with room is left, so 2 is the most that can be sent. The only place the source can still reach, A, is on one side of the narrowest cut. | 2 | 8 |
In all, 8 roads looked along. The formula from section 4, , gives at : the same.
where you meet it
It began with rail lines, and it still finds the cheapest place to split a network.
Rail lines
Lester Ford and Delbert Fulkerson's 1956 paper opens on a rail network between two cities, a question from T. E. Harris. Harris's report with F. S. Ross, for the US Air Force, looked for the narrowest cut of the Soviet rail network.
source: L. R. Ford and D. R. Fulkerson, Maximal flow through a network (opens in a new tab), Canadian Journal of Mathematics 8, A. Schrijver, a history of the problem (opens in a new tab), Mathematical Programming 91(3), and the books' volume four, chapter 42
Selecting part of a photograph
You pick a few pixels to keep and a few to drop. A new source has a road to each one to keep, and each one to drop has a road to a new sink. Each pixel is a place, joined to its neighbours by roads whose limits grow the more alike they look. The narrowest cut is the cheapest border to draw.
source: Y. Boykov and M.-P. Jolly, Interactive graph cuts (opens in a new tab), ICCV 2001, and the books' volume four, chapter 42
networkx and SciPy
Both, ready-made Python code, offer this page's method as edmonds_karp. Unless told otherwise, their maximum_flow takes a different method, preflow_push in networkx and dinic in SciPy.
source: J. Edmonds and R. M. Karp, their 1972 paper (opens in a new tab), Journal of the ACM 19(2), the networkx source, edmondskarp.py (opens in a new tab) and maxflow.py (opens in a new tab), and the SciPy source, _flow.pyx (opens in a new tab)
what is used instead
For large maps, use ready-made code's faster method.
how it compares
This page's method is the Edmonds-Karp algorithm, one kind of Ford-Fulkerson method. With no taking back, a run can stop short. The small map stops at 3 if A, B, F, G goes first, and reaches 5 if A, E, F, G does. With taking back and any way, each way sends at least 1 when the limits are whole, so the run ends. But its ways can grow with the limits, as the map below shows.
| method | which way | takes back | ways at most |
|---|---|---|---|
| no taking back | any with room | no | can stop below the most |
| Ford and Fulkerson | any with room | yes | the amount sent, with whole limits |
| Edmonds and Karp, this page's | fewest steps | yes | , whatever the limits |