2018-03-08 20:52:16 +00:00
|
|
|
# Ford-Fulkerson Algorithm for Maximum Flow Problem
|
|
|
|
"""
|
|
|
|
Description:
|
|
|
|
(1) Start with initial flow as 0;
|
|
|
|
(2) Choose augmenting path from source to sink and add path to flow;
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def bfs(graph, s, t, parent):
|
2018-03-08 20:52:16 +00:00
|
|
|
# Return True if there is node that has not iterated.
|
2019-10-05 05:14:13 +00:00
|
|
|
visited = [False] * len(graph)
|
|
|
|
queue = []
|
2018-03-08 20:52:16 +00:00
|
|
|
queue.append(s)
|
|
|
|
visited[s] = True
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2018-03-08 20:52:16 +00:00
|
|
|
while queue:
|
|
|
|
u = queue.pop(0)
|
|
|
|
for ind in range(len(graph[u])):
|
2020-05-22 06:10:11 +00:00
|
|
|
if visited[ind] is False and graph[u][ind] > 0:
|
2018-03-08 20:52:16 +00:00
|
|
|
queue.append(ind)
|
|
|
|
visited[ind] = True
|
|
|
|
parent[ind] = u
|
|
|
|
|
|
|
|
return True if visited[t] else False
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def ford_fulkerson(graph, source, sink):
|
2018-03-08 20:52:16 +00:00
|
|
|
# This array is filled by BFS and to store path
|
2019-10-05 05:14:13 +00:00
|
|
|
parent = [-1] * (len(graph))
|
|
|
|
max_flow = 0
|
2022-10-12 22:54:20 +00:00
|
|
|
while bfs(graph, source, sink, parent):
|
2018-03-08 20:52:16 +00:00
|
|
|
path_flow = float("Inf")
|
|
|
|
s = sink
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
while s != source:
|
2018-03-08 20:52:16 +00:00
|
|
|
# Find the minimum value in select path
|
2019-10-05 05:14:13 +00:00
|
|
|
path_flow = min(path_flow, graph[parent[s]][s])
|
2018-03-08 20:52:16 +00:00
|
|
|
s = parent[s]
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
max_flow += path_flow
|
2018-03-08 20:52:16 +00:00
|
|
|
v = sink
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
while v != source:
|
2018-03-08 20:52:16 +00:00
|
|
|
u = parent[v]
|
|
|
|
graph[u][v] -= path_flow
|
|
|
|
graph[v][u] += path_flow
|
|
|
|
v = parent[v]
|
|
|
|
return max_flow
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
graph = [
|
|
|
|
[0, 16, 13, 0, 0, 0],
|
|
|
|
[0, 0, 10, 12, 0, 0],
|
|
|
|
[0, 4, 0, 0, 14, 0],
|
|
|
|
[0, 0, 9, 0, 0, 20],
|
|
|
|
[0, 0, 0, 7, 0, 4],
|
|
|
|
[0, 0, 0, 0, 0, 0],
|
|
|
|
]
|
2018-03-08 20:52:16 +00:00
|
|
|
|
|
|
|
source, sink = 0, 5
|
2022-10-12 22:54:20 +00:00
|
|
|
print(ford_fulkerson(graph, source, sink))
|