Skip to content

Commit 7ae1534

Browse files
authored
fix problem ford_fulkerson.py
1 parent c3d4b9e commit 7ae1534

1 file changed

Lines changed: 7 additions & 13 deletions

File tree

networking_flow/ford_fulkerson.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,3 @@
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-
101
graph = [
112
[0, 16, 13, 0, 0, 0],
123
[0, 0, 10, 12, 0, 0],
@@ -16,7 +7,6 @@
167
[0, 0, 0, 0, 0, 0],
178
]
189

19-
2010
def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> bool:
2111
"""
2212
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) ->
5444
parents[ind] = u
5545
return visited[sink]
5646

57-
5847
def ford_fulkerson(graph: list, source: int, sink: int) -> int:
5948
"""
6049
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:
9988

10089
while v != source:
10190
u = parent[v]
91+
# Update residual capacities
10292
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)
10396
graph[v][u] += path_flow
10497
v = parent[v]
10598

10699
return max_flow
107100

108-
109101
if __name__ == "__main__":
110102
from doctest import testmod
111103

112104
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

Comments
 (0)