Skip to content

Fix Ford-Fulkerson Implementation to Handle Residual Graph Correctly #12785

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
Next Next commit
fix problem ford_fulkerson.py
  • Loading branch information
lighting9999 authored Jun 7, 2025
commit 7ae1534e6855ba671e77646ba277739b80fef70f
20 changes: 7 additions & 13 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 All @@ -16,7 +7,6 @@
[0, 0, 0, 0, 0, 0],
]


def breadth_first_search(graph: list, source: int, sink: int, parents: list) -> bool:
"""
This function returns True if there is a node that has not iterated.
Expand Down Expand Up @@ -54,7 +44,6 @@
parents[ind] = u
return visited[sink]


def ford_fulkerson(graph: list, source: int, sink: int) -> int:
"""
This function returns the maximum flow from source to sink in the given graph.
Expand Down Expand Up @@ -99,15 +88,20 @@

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)

Check failure on line 95 in networking_flow/ford_fulkerson.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

networking_flow/ford_fulkerson.py:95:89: E501 Line too long (93 > 88)
graph[v][u] += path_flow
v = parent[v]

return max_flow


if __name__ == "__main__":
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) = }")
Loading