1. Understand the Goal: The user wants a computer program that implements the Ford-Fulkerson algorithm. This algorithm solves the maximum flow problem in a flow network.
-
Identify the Core Concepts:
- Flow Network: A directed graph with a source (s) and a sink (t), where edges have capacities.
- Capacity Constraint: Flow on an edge cannot exceed capacity.
- Flow Conservation: Input flow equals output flow for all nodes except s and t.
- Residual Graph: Represents how much more flow can be pushed. Edges can be reversed to allow "undoing" flow.
- Augmenting Path: A path from s to t in the residual graph where every edge has positive residual capacity.
- The Algorithm:
- Initialize flow to 0.
- While an augmenting path exists in the residual graph:
a. Find the path (usually BFS or DFS). BFS guarantees the shortest path (Edmonds-Karp), while DFS is the generic Ford-Fulkerson. I should probably provide the DFS version as it's the standard textbook definition of Ford-Fulkerson, but mention BFS (Edmonds-Karp) as an optimization for polynomial time complexity.
b. Determine the bottleneck capacity (minimum residual capacity along the path).
c. Update the flow on the original edges and the residual capacities on the residual graph.
- Return the max flow.
-
Select a Programming Language: Python is generally the most accessible for algorithms due to its readability. I'll use Python.
-
Drafting the Implementation (Mental or Scratchpad):
-
Input representation: An adjacency matrix or adjacency list? Adjacency lists are better for sparse graphs, but matrices are easier to implement for small examples. Let's go with a class-based approach using an adjacency matrix for simplicity in handling capacities, or a dictionary of dictionaries for a sparse representation. Actually, a 2D array (list of lists) is very standard for these demonstrations. Let's stick to a 2D array (matrix) for the graph capacity.
-
BFS/DFS Function: Needs to find a path from source to sink and store the path to trace back the bottleneck.
parent array: parent[i] stores the predecessor of node i in the path.
-
The Main Loop:
max_flow = 0
- Loop while
bfs returns true:
- Find path flow (min capacity in path).
- Update residual capacities:
graph[u][v] -= path_flow
graph[v][u] += path_flow
max_flow += path_flow
-
Refining the Implementation:
- Choice of Search: DFS is conceptually simpler for Ford-Fulkerson. BFS is Edmonds-Karp. The prompt asks for "Ford-Fulkerson". Strictly speaking, Ford-Fulkerson is the method (find augmenting path, augment), and the search method is a detail. However, using DFS is the classic definition. If I use BFS, I should explicitly call it Edmonds-Karp. To be safe and generic, I will write a version using BFS (because it's generally more robust against certain edge cases with irrational capacities, though integers are fine with DFS) but label it clearly, or just stick to the DFS logic. Let's stick to BFS because it's O(VE2) whereas generic FF can be O(E⋅f) which depends on max flow value. For a "program", the BFS version (Edmonds-Karp) is practically preferred.
-
Writing the Code (Python):
- Class
MaxFlow.
__init__: takes number of vertices.
add_edge: populate the capacity matrix.
bfs: standard BFS to find if there is a path from s to t.
ford_fulkerson: the logic described in step 2.
-
Adding Comments and Explanation:
- Explain the Residual Graph.
- Explain the Augmenting Path.
- Explain the Time Complexity.
-
Reviewing the Code Structure:
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ROW = len(graph)
def bfs(self, s, t, parent):
# Standard BFS logic
# Returns True if path exists
pass
def ford_fulkerson(self, source, sink):
max_flow = 0
parent = [-1] * self.ROW
while self.bfs(source, sink, parent):
# Find bottleneck
path_flow = float("Inf")
s = sink
while(s != source):
path_flow = min(path_flow, self.graph[parent[s]][s])
s = parent[s]
# Update capacities
v = sink
while(v != source):
u = parent[v]
self.graph[u][v] -= path_flow
self.graph[v][u] += path_flow
v = parent[v]
max_flow += path_flow
return max_flow
-
Edge Cases:
- What if graph is empty? (The
len check handles it).
- What if no path exists initially? (BFS returns false immediately, returns 0).
-
Final Output Generation:
- Python code block.
- Example usage block (create a graph, run it, print result).
- Brief explanation of how it works.
-
Self-Correction during drafting: I initially thought about using dfs because the prompt didn't ask for Edmonds-Karp. However, generic Ford-Fulkerson using DFS can run indefinitely on graphs with irrational capacities (theoretical edge case) or poorly on integer capacities. The BFS version is the standard "good" implementation. I will implement it using BFS but title the method ford_fulkerson. I will clarify in the text that this specific implementation uses BFS (Edmonds-Karp) to find paths, which is the standard efficient approach.
Let's refine the add_edge logic. Using a raw adjacency matrix in the __init__ is easy for the snippet, but a method to add edges makes it more user-friendly. I'll stick to passing the matrix in __init__ as it's cleaner for a standalone script demonstration.
-
Code Polish: Ensure variable names are clear (u, v, s, t are standard, but maybe source, sink are better for readability). Add comments explaining the residual capacity update graph[v][u] += path_flow.
Let's prepare the example graph.
Standard example:
0 -> 1 (16)
0 -> 2 (13)
1 -> 2 (10)
2 -> 1 (4)
...etc.
This looks good. Ready to generate response.
Here is a complete implementation of the Ford-Fulkerson algorithm using the Edmonds-Karp strategy (which uses Breadth-First Search to find augmenting paths) in Python.
This implementation uses an Adjacency Matrix to represent the graph capacities.
Python Implementation
from collections import deque
class Graph:
def __init__(self, graph):
# graph is a 2D array (adjacency matrix) representing capacities
# self.graph stores the residual graph
self.graph = graph
self.ROW = len(graph)
def bfs(self, s, t, parent):
"""
Performs BFS to find a path from source 's' to sink 't'
in the residual graph. Returns True if a path exists.
Also fills the parent array to store the path.
"""
visited = [False] * self.ROW
queue = deque()
queue.append(s)
visited[s] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(self.graph[u]):
# If node v is not visited and there is available capacity
if not visited[v] and capacity > 0:
queue.append(v)
visited[v] = True
parent[v] = u
if v == t:
return True
return False
def ford_fulkerson(self, source, sink):
"""
Returns the maximum flow from source to sink.
"""
max_flow = 0
parent = [-1] * self.ROW
# Augment the flow while there is a path from source to sink
while self.bfs(source, sink, parent):
# Find the minimum residual capacity of the edges along the
# path filled by BFS (the bottleneck capacity)
path_flow = float("Inf")
s = sink
while s != source:
path_flow = min(path_flow, self.graph[parent[s]][s])
s = parent[s]
# Add the path flow to the total flow
max_flow += path_flow
# Update residual capacities of the edges and reverse edges
v = sink
while v != source:
u = parent[v]
self.graph[u][v] -= path_flow
self.graph[v][u] += path_flow
v = parent[v]
return max_flow
# --- Example Usage ---
if __name__ == "__main__":
# Example Graph (Adjacency Matrix)
# Values represent capacities of edges.
# Example Network:
#
# (0) --16--> (1)
# | |
# 13 10
# | |
# v v
# (2) --4--> (1) <--20-- (3)
# | |
# 14 7
# | |
# v v
# (3) <--9-- (2) --4--> (3)
#
# Simplified standard example:
# 0 is Source, 3 is Sink.
graph_data = [
[0, 16, 13, 0, 0, 0], # Edges from Node 0
[0, 0, 10, 12, 0, 0], # Edges from Node 1
[0, 4, 0, 0, 14, 0], # Edges from Node 2
[0, 0, 9, 0, 0, 20], # Edges from Node 3
[0, 0, 0, 7, 0, 4], # Edges from Node 4
[0, 0, 0, 0, 0, 0] # Edges from Node 5
]
g = Graph(graph_data)
source = 0
sink = 5
print("The maximum possible flow is %d" % g.ford_fulkerson(source, sink))
How it works
- Residual Graph: The algorithm maintains a "residual graph" which indicates how much more flow can be pushed through an edge. Initially, this is identical to the input capacities.
- BFS (Finding a Path): It uses Breadth-First Search to find any path from the source to the sink that still has available capacity.
- Bottleneck: Once a path is found (e.g., 0→1→3→5), it determines the "bottleneck" value. This is the smallest capacity on that path. This is the amount of flow we can push right now.
- Update Capacities:
- It subtracts the flow from the forward edges (reducing available capacity).
- It adds the flow to the reverse edges. This is the crucial step that allows the algorithm to "undo" bad decisions. If we send flow A→B, sending it back in a future step effectively cancels the previous flow.
Complexity
- Time Complexity: O(VE2) where V is the number of vertices and E is the number of edges. This specific implementation is technically the Edmonds-Karp algorithm because it uses BFS, which is a specific implementation of Ford-Fulkerson. (The generic Ford-Fulkerson using DFS can be unbounded for irrational capacities).