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
Prev Previous commit
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jun 7, 2025
commit 13e974e7f20260a907464d608e492eae1adf5745
7 changes: 6 additions & 1 deletion networking_flow/ford_fulkerson.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
[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 @@ -44,6 +45,7 @@ def breadth_first_search(graph: list, source: int, sink: int, parents: list) ->
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 @@ -92,12 +94,15 @@ def ford_fulkerson(graph: list, source: int, sink: int) -> int:
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] = (
0 # Explicitly initialize if needed (though usually already 0)
)
graph[v][u] += path_flow
v = parent[v]

return max_flow


if __name__ == "__main__":
from doctest import testmod

Expand Down