1. Understand the Goal: The user wants a program to find the maximum flow in a flow network.
-
Identify the Algorithm: The most common and standard algorithm for this is the Ford-Fulkerson method using BFS (Breadth-First Search), also known as the Edmonds-Karp algorithm. It's efficient enough for general cases and easier to implement correctly than Push-Relabel or Dinic's for a general-purpose example (though Dinic's is faster, Edmonds-Karp is usually the "standard" textbook implementation). I'll stick with Edmonds-Karp for clarity and robustness against infinite loops (due to BFS finding the shortest augmenting path).
-
Determine the Input/Output:
- Input: A graph representing the network. It needs nodes, edges, capacities, a source node (s), and a sink node (t).
- Output: The integer value of the maximum flow. (Optionally, the actual flow on each edge).
-
Select a Programming Language: Python is highly readable and great for algorithmic demonstrations. C++ is also good for performance. I will provide the solution in Python because it's accessible, but I should structure it in a way that a graph is built easily (adjacency matrix or adjacency list).
- Decision: Adjacency Matrix is easy to code but O(V2) space. Adjacency List is O(E) space but slightly more complex to handle residual capacities.
- Refinement: Since max flow problems often involve sparse graphs, an Adjacency List is better. However, for a simple implementation, an Adjacency Matrix (if V is small) is easiest to read.
- Better Approach: Use a
graph dictionary of dictionaries (Python) or a 2D array. Let's stick to a 2D array (Adjacency Matrix) for the simplest implementation of Edmonds-Karp, as it maps directly to the capacity constraint Cuv. If V is large, lists are needed, but for a generic "create a program" request, the matrix approach is often the most intuitive for the math (C[u][v]).
Actually, let's use an adjacency list representation using a class to make it more professional and scalable, or just a clean function.
Let's stick to Python with an Adjacency Matrix (or a dictionary of dictionaries) for simplicity in the BFS step. Let's use a 2D list (matrix) for the capacities.
-
Drafting the Algorithm (Edmonds-Karp):
- Initialize
max_flow = 0.
- Create a
residual_graph initialized with the capacities.
- Loop:
- Run BFS on
residual_graph to find a path from Source to Sink.
- BFS returns the path (or parent pointers) and the bottleneck capacity (minimum capacity on that path).
- If no path exists, break.
- Update
residual_graph:
- For each edge (u,v) in path:
residual[u][v] -= bottleneck, residual[v][u] += bottleneck.
max_flow += bottleneck.
- Return
max_flow.
-
Writing the Code (Mental Draft):
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ROW = len(graph)
def bfs(self, s, t, parent):
visited = [False] * self.ROW
queue = [s]
visited[s] = True
while queue:
u = queue.pop(0)
for v, val in enumerate(self.graph[u]):
if not visited[v] and val > 0:
queue.append(v)
visited[v] = True
parent[v] = u
if v == t: return True
return False
def edmonds_karp(self, source, sink):
parent = [-1] * self.ROW
max_flow = 0
while self.bfs(source, sink, parent):
# find bottleneck
path_flow = float("Inf")
v = sink
while v != source:
u = parent[v]
path_flow = min(path_flow, self.graph[u][v])
v = u
# update residuals
v = sink
while v != source:
u = parent[v]
self.graph[u][v] -= path_flow
self.graph[v][u] += path_flow
v = u
max_flow += path_flow
return max_flow
-
Refining the Solution:
- The matrix approach works well.
- I should add comments explaining the residual graph concept (forward edge decreases, backward edge increases).
- I need to provide a driver code (example) to show how to use it. A classic example is a graph with 6 nodes.
-
Alternative Language (C++):
- Some users prefer C++ for competitive programming. It might be nice to offer both or just stick to Python for readability. I'll provide the Python solution as the primary one, as it's pseudo-code-like, but if I were to do C++, I'd use
std::vector<std::vector<int>>. Let's stick to Python for clarity unless requested otherwise, but maybe make the Python code very clean.
-
Structure of the Output:
- Explanation: Briefly explain the concept (Flow network, Residual graph, Augmenting path).
- The Code: Python implementation of Edmonds-Karp.
- Example Usage: A concrete graph input.
- Time Complexity: Mention it (O(VE2) for Edmonds-Karp).
-
Self-Correction/Review during drafting:
- Wait, is the input matrix the capacity or the flow? It should be the Capacity.
- Important: The
graph passed to the class will be mutated. I should copy it if I want to preserve the original capacities, or just state that it modifies the graph. In this context, mutating the residual graph is standard.
This algorithm is chosen because it uses Breadth-First Search (BFS) to find the shortest augmenting path, guaranteeing termination and polynomial time complexity (O(VE2)), whereas standard Depth-First Search (DFS) implementations can potentially run forever on networks with irrational capacities.
The Solution (Python)
from collections import deque
class MaxFlow:
def __init__(self, num_nodes):
self.num_nodes = num_nodes
# Initialize capacity adjacency matrix with 0s
# capacity[u][v] represents the capacity of edge u -> v
self.capacity = [[0] * num_nodes for _ in range(num_nodes)]
# Adjacency list to keep track of neighbors for faster iteration
self.adj = [[] for _ in range(num_nodes)]
def add_edge(self, u, v, cap):
"""
Adds a directed edge from u to v with given capacity.
"""
self.capacity[u][v] += cap
# Add to adjacency list if not already present (basic check)
if v not in self.adj[u]:
self.adj[u].append(v)
if u not in self.adj[v]:
self.adj[v].append(u) # Add reverse edge for residual graph traversal
def bfs(self, s, t, parent):
"""
Returns True if there is a path from source 's' to sink 't'
in the residual graph. Also fills parent[] to store the path.
"""
visited = [False] * self.num_nodes
queue = deque()
queue.append(s)
visited[s] = True
parent[s] = -1
while queue:
u = queue.popleft()
for v in self.adj[u]:
# If node v is not visited and there is available capacity
if not visited[v] and self.capacity[u][v] > 0:
# If we reached the sink, we are done
if v == t:
parent[v] = u
return True
queue.append(v)
visited[v] = True
parent[v] = u
return False
def get_max_flow(self, source, sink):
"""
Computes the maximum flow from source to sink using Edmonds-Karp.
"""
max_flow = 0
parent = [-1] * self.num_nodes
# Loop while there is a path from source to sink in the residual graph
while self.bfs(source, sink, parent):
# 1. Find the maximum possible flow (bottleneck) on the path found by BFS
path_flow = float('Inf')
v = sink
while v != source:
u = parent[v]
path_flow = min(path_flow, self.capacity[u][v])
v = u
# 2. Update residual capacities of the edges and reverse edges
v = sink
while v != source:
u = parent[v]
self.capacity[u][v] -= path_flow
self.capacity[v][u] += path_flow
v = u
# 3. Add path flow to overall flow
max_flow += path_flow
return max_flow
# --- Usage Example ---
if __name__ == "__main__":
# Example Graph:
# 0 (Source) --16--> 1
# 0 --13--> 2
# 1 --10--> 2
# 1 --12--> 3
# 2 --4--> 1
# 2 --14--> 3 (Sink)
# Note: Indices 0 to 3 (4 nodes total)
num_vertices = 4
graph = MaxFlow(num_vertices)
# Adding edges (u, v, capacity)
graph.add_edge(0, 1, 16)
graph.add_edge(0, 2, 13)
graph.add_edge(1, 2, 10)
graph.add_edge(1, 3, 12)
graph.add_edge(2, 1, 4)
graph.add_edge(2, 3, 14)
source = 0
sink = 3
print(f"Maximum Flow: {graph.get_max_flow(source, sink)}")
How it Works
- Residual Graph: The algorithm doesn't modify the "original" graph permanently; instead, it maintains a "residual graph" where
capacity[u][v] represents how much more flow can be pushed from u to v.
- BFS (Augmenting Path): The
bfs function looks for any path from Start to End where the capacity is greater than 0. Because it uses BFS, it finds the shortest path (in terms of edges) first.
- Bottleneck: Once a path is found, we look at every edge in that path and find the one with the smallest capacity. That is the maximum amount of water we can push through that specific pipe right now.
- Flow Update: We subtract that "bottleneck" amount from the forward edges (using up capacity) and add it to the reverse edges. Adding flow to the reverse edge represents the ability to "undo" or redirect flow later if a better path is found.
- Repeat: This continues until no path exists from Source to Sink with capacity > 0.
Complexity
- Time Complexity: O(VE2) where V is the number of vertices and E is the number of edges.
- Space Complexity: O( for the adjacency matrix (efficient for dense graphs). For sparse graphs, an adjacency list of objects could be used to save space.