Skip to content

Commit dc2b575

Browse files
authored
Add doctests to networking_flow/minimum_cut.py (#1126)
1 parent c74fd0c commit dc2b575

File tree

1 file changed

+32
-25
lines changed

1 file changed

+32
-25
lines changed

networking_flow/minimum_cut.py

+32-25
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
# Minimum cut on Ford_Fulkerson algorithm.
2-
2+
3+
test_graph = [
4+
[0, 16, 13, 0, 0, 0],
5+
[0, 0, 10, 12, 0, 0],
6+
[0, 4, 0, 0, 14, 0],
7+
[0, 0, 9, 0, 0, 20],
8+
[0, 0, 0, 7, 0, 4],
9+
[0, 0, 0, 0, 0, 0],
10+
]
11+
12+
313
def BFS(graph, s, t, parent):
414
# Return True if there is node that has not iterated.
5-
visited = [False]*len(graph)
6-
queue=[]
7-
queue.append(s)
15+
visited = [False] * len(graph)
16+
queue = [s]
817
visited[s] = True
9-
18+
1019
while queue:
1120
u = queue.pop(0)
1221
for ind in range(len(graph[u])):
@@ -16,26 +25,30 @@ def BFS(graph, s, t, parent):
1625
parent[ind] = u
1726

1827
return True if visited[t] else False
19-
28+
29+
2030
def mincut(graph, source, sink):
21-
# This array is filled by BFS and to store path
22-
parent = [-1]*(len(graph))
23-
max_flow = 0
31+
"""This array is filled by BFS and to store path
32+
>>> mincut(test_graph, source=0, sink=5)
33+
[(1, 3), (4, 3), (4, 5)]
34+
"""
35+
parent = [-1] * (len(graph))
36+
max_flow = 0
2437
res = []
25-
temp = [i[:] for i in graph] # Record orignial cut, copy.
26-
while BFS(graph, source, sink, parent) :
38+
temp = [i[:] for i in graph] # Record orignial cut, copy.
39+
while BFS(graph, source, sink, parent):
2740
path_flow = float("Inf")
2841
s = sink
2942

30-
while(s != source):
43+
while s != source:
3144
# Find the minimum value in select path
32-
path_flow = min (path_flow, graph[parent[s]][s])
45+
path_flow = min(path_flow, graph[parent[s]][s])
3346
s = parent[s]
3447

35-
max_flow += path_flow
48+
max_flow += path_flow
3649
v = sink
37-
38-
while(v != source):
50+
51+
while v != source:
3952
u = parent[v]
4053
graph[u][v] -= path_flow
4154
graph[v][u] += path_flow
@@ -44,16 +57,10 @@ def mincut(graph, source, sink):
4457
for i in range(len(graph)):
4558
for j in range(len(graph[0])):
4659
if graph[i][j] == 0 and temp[i][j] > 0:
47-
res.append((i,j))
60+
res.append((i, j))
4861

4962
return res
5063

51-
graph = [[0, 16, 13, 0, 0, 0],
52-
[0, 0, 10 ,12, 0, 0],
53-
[0, 4, 0, 0, 14, 0],
54-
[0, 0, 9, 0, 0, 20],
55-
[0, 0, 0, 7, 0, 4],
56-
[0, 0, 0, 0, 0, 0]]
5764

58-
source, sink = 0, 5
59-
print(mincut(graph, source, sink))
65+
if __name__ == "__main__":
66+
print(mincut(test_graph, source=0, sink=5))

0 commit comments

Comments
 (0)