|
1 | | -""" |
2 | | -Ford-Fulkerson Algorithm for Maximum Flow Problem |
3 | | -* https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm |
4 | | -
|
5 | | -Description: |
6 | | - (1) Start with initial flow as 0 |
7 | | - (2) Choose the augmenting path from source to sink and add the path to flow |
8 | | -""" |
9 | | - |
10 | 1 | graph = [ |
11 | 2 | [0, 16, 13, 0, 0, 0], |
12 | 3 | [0, 0, 10, 12, 0, 0], |
|
16 | 7 | [0, 0, 0, 0, 0, 0], |
17 | 8 | ] |
18 | 9 |
|
19 | | - |
20 | 10 | def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> bool: |
21 | 11 | """ |
22 | 12 | This function returns True if there is a node that has not iterated. |
@@ -54,7 +44,6 @@ def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> |
54 | 44 | parents[ind] = u |
55 | 45 | return visited[sink] |
56 | 46 |
|
57 | | - |
58 | 47 | def ford_fulkerson(graph: list, source: int, sink: int) -> int: |
59 | 48 | """ |
60 | 49 | This function returns the maximum flow from source to sink in the given graph. |
@@ -99,15 +88,20 @@ def ford_fulkerson(graph: list, source: int, sink: int) -> int: |
99 | 88 |
|
100 | 89 | while v != source: |
101 | 90 | u = parent[v] |
| 91 | + # Update residual capacities |
102 | 92 | graph[u][v] -= path_flow |
| 93 | + # Ensure reverse edge exists |
| 94 | + if graph[v][u] == 0: |
| 95 | + graph[v][u] = 0 # Explicitly initialize if needed (though usually already 0) |
103 | 96 | graph[v][u] += path_flow |
104 | 97 | v = parent[v] |
105 | 98 |
|
106 | 99 | return max_flow |
107 | 100 |
|
108 | | - |
109 | 101 | if __name__ == "__main__": |
110 | 102 | from doctest import testmod |
111 | 103 |
|
112 | 104 | testmod() |
113 | | - print(f"{ford_fulkerson(graph, source=0, sink=5) = }") |
| 105 | + # Make a copy of the original graph to preserve it |
| 106 | + graph_copy = [row[:] for row in graph] |
| 107 | + print(f"{ford_fulkerson(graph_copy, source=0, sink=5) = }") |
0 commit comments