1
1
# 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
+
3
13
def BFS (graph , s , t , parent ):
4
14
# 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 ]
8
17
visited [s ] = True
9
-
18
+
10
19
while queue :
11
20
u = queue .pop (0 )
12
21
for ind in range (len (graph [u ])):
@@ -16,26 +25,30 @@ def BFS(graph, s, t, parent):
16
25
parent [ind ] = u
17
26
18
27
return True if visited [t ] else False
19
-
28
+
29
+
20
30
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
24
37
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 ):
27
40
path_flow = float ("Inf" )
28
41
s = sink
29
42
30
- while ( s != source ) :
43
+ while s != source :
31
44
# 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 ])
33
46
s = parent [s ]
34
47
35
- max_flow += path_flow
48
+ max_flow += path_flow
36
49
v = sink
37
-
38
- while ( v != source ) :
50
+
51
+ while v != source :
39
52
u = parent [v ]
40
53
graph [u ][v ] -= path_flow
41
54
graph [v ][u ] += path_flow
@@ -44,16 +57,10 @@ def mincut(graph, source, sink):
44
57
for i in range (len (graph )):
45
58
for j in range (len (graph [0 ])):
46
59
if graph [i ][j ] == 0 and temp [i ][j ] > 0 :
47
- res .append ((i ,j ))
60
+ res .append ((i , j ))
48
61
49
62
return res
50
63
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 ]]
57
64
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