programming-examples/python/Algorithms/maxflow_fordfulkerson_simple.py
2019-11-15 12:59:38 +01:00

29 lines
713 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# https://en.wikipedia.org/wiki/FordFulkerson_algorithm in O(V^2 * flow)
def max_flow(cap, s, t):
def augment_path(cap, visited, i, t):
if i == t:
return True
visited[i] = True
for j in range(len(cap)):
if not visited[j] and cap[i][j] > 0 and augment_path(cap, visited, j, t):
cap[i][j] -= 1
cap[j][i] += 1
return True
return False
flow = 0
while True:
if not augment_path(cap, [False] * len(cap), s, t):
return flow
flow += 1
def test():
capacity = [[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]]
assert max_flow(capacity, 0, 3) == 2
test()