forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum_cut.py
66 lines (52 loc) · 1.61 KB
/
minimum_cut.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Minimum cut on Ford_Fulkerson algorithm.
test_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],
]
defbfs(graph, s, t, parent):
# Return True if there is node that has not iterated.
visited= [False] *len(graph)
queue= [s]
visited[s] =True
whilequeue:
u=queue.pop(0)
forindinrange(len(graph[u])):
ifvisited[ind] isFalseandgraph[u][ind] >0:
queue.append(ind)
visited[ind] =True
parent[ind] =u
returnvisited[t]
defmincut(graph, source, sink):
"""This array is filled by BFS and to store path
>>> mincut(test_graph, source=0, sink=5)
[(1, 3), (4, 3), (4, 5)]
"""
parent= [-1] * (len(graph))
max_flow=0
res= []
temp= [i[:] foriingraph] # Record original cut, copy.
whilebfs(graph, source, sink, parent):
path_flow=float("Inf")
s=sink
whiles!=source:
# Find the minimum value in select path
path_flow=min(path_flow, graph[parent[s]][s])
s=parent[s]
max_flow+=path_flow
v=sink
whilev!=source:
u=parent[v]
graph[u][v] -=path_flow
graph[v][u] +=path_flow
v=parent[v]
foriinrange(len(graph)):
forjinrange(len(graph[0])):
ifgraph[i][j] ==0andtemp[i][j] >0:
res.append((i, j))
returnres
if__name__=="__main__":
print(mincut(test_graph, source=0, sink=5))