Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions networking_flow/ford_fulkerson.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
Ford-Fulkerson Algorithm for Maximum Flow Problem
* https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm

Description:
(1) Start with initial flow as 0
(2) Choose the augmenting path from source to sink and add the path to flow
"""

graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
Expand Down Expand Up @@ -99,7 +90,13 @@ def ford_fulkerson(graph: list, source: int, sink: int) -> int:

while v != source:
u = parent[v]
# Update residual capacities
graph[u][v] -= path_flow
# Ensure reverse edge exists
if graph[v][u] == 0:
graph[v][u] = (
0 # Explicitly initialize if needed (though usually already 0)
)
graph[v][u] += path_flow
v = parent[v]

Expand All @@ -110,4 +107,6 @@ def ford_fulkerson(graph: list, source: int, sink: int) -> int:
from doctest import testmod

testmod()
print(f"{ford_fulkerson(graph, source=0, sink=5) = }")
# Make a copy of the original graph to preserve it
graph_copy = [row[:] for row in graph]
print(f"{ford_fulkerson(graph_copy, source=0, sink=5) = }")