The user wants a program to find the maximum flow in a flow network.
I need to choose an algorithm to implement. Common choices are:
Ford-Fulkerson method using DFS (Edmonds-Karp uses BFS).
Edmonds-Karp algorithm (Ford-Fulkerson with BFS).
Dinic's algorithm (more efficient).
For a general-purpose "create a program" request without specific size constraints or performance requirements, the Edmonds-Karp algorithm is a solid choice. It's easier to implement than Dinic's but guarantees polynomial time complexity (O(VE2)), unlike the basic Ford-Fulkerson with DFS which can be slow or get stuck in irrational capacities (though unlikely with integers). Dinic's is better (O(V2E) or O(VElogV)), but Edmonds-Karp is often sufficient for learning and moderate input sizes.
However, since I want to provide a high-quality answer, I should probably provide Dinic's algorithm or Edmonds-Karp. Let's stick with Edmonds-Karp for clarity and ease of understanding, as it's the standard "introduction" to Max Flow algorithms after the basic Ford-Fulkerson concept. Actually, Dinic's is quite standard in competitive programming, but Edmonds-Karp is conceptually simpler to explain. I'll implement Edmonds-Karp because it maps directly to the concept of "finding augmenting paths via shortest path (BFS)".
Components of the Program:
Graph Representation: Adjacency matrix or Adjacency list? Adjacency lists are generally better for sparse graphs, which are common. Adjacency matrices are easier to code but worse space-wise. I'll use an adjacency list where each entry stores the destination, capacity, and a reference (index) to the reverse edge for residual graph updates.
Input/Output: Needs to take graph data (nodes, edges, source, sink) and output the max flow value.
Algorithm Logic:
Initialize flow to 0.
While there is a path from source to sink in the residual graph (found via BFS):
Find the bottleneck capacity (minimum residual capacity on that path).
Language Choice: Python is readable and great for algorithmic demonstrations. C++ is faster. I'll provide the solution in Python because it's accessible, and maybe a C++ version for performance enthusiasts if requested, but usually, one clear implementation is best. I will stick to Python.
Step-by-Step Implementation Plan:
Define a class Edge (or use tuples/dicts) to store destination, capacity, and reverse edge index.
Define a function add_edge(u, v, capacity) to build the graph and the residual graph (adding a forward edge with capacity and a backward edge with 0).
Implement max_flow(source, sink):
Loop while True:
Run BFS to find a path from source to sink and store parents to reconstruct the path.
If BFS fails, break.
Trace back parents to find path_flow (min capacity on path).
Update edges based on path_flow.
Add to max_flow.
Create a driver code section to demonstrate it working.
Refining the Data Structure:
Using a simple adjacency list graph = [[] for _ in range(n)].
Each element graph[u] is a list of edges.
An edge can be a list/dict: [v, capacity, rev_index].
When adding u→v with cap C:
Add [v, C, len(graph[v])] to graph[u].
Add [u, 0, len(graph[u]) - 1] to graph[v].
The rev_index helps quickly find the reverse edge. If we are at edge graph[u][i], its reverse is graph[v][graph[u][i][2]].
Edge Case Considerations:
Disconnected graph (BFS returns no path immediately).
Source == Sink (infinite flow usually, or 0 depending on definition, usually just return 0 or handle).
Integer overflow? Python handles large integers automatically. C++ would need long long.
Let's write the code mentally first.
python
def bfs(s, t, parent):
# standard bfs
# mark s visited
# queue q
# while q:
# u = q.pop
# for i, edge in enumerate(graph[u]):
# if not visited[edge.v] and edge.cap > 0:
# parent[edge.v] = (u, i)
# visited[edge.v] = True
# q.append(edge.v)
# return visited[t]
The prompt asks for "a program". I will provide a complete Python script with a class structure for better organization.
Structure:
MaxFlow class.
__init__: initializes N and adjacency list.
add_edge: handles residual graph construction.
bfs: helper to find shortest augmenting path.
edmonds_karp: main loop.
main: example usage.
I should briefly explain why this algorithm works (concept of residual graph, augmenting paths) to make the answer educational.
Let's review the complexity. O(VE2). With V=100,E=1000, it's fine. With , it's ops... maybe a bit slow (seconds). For large inputs, Dinic is better. However, Edmonds-Karp is the standard implementation for "write a max flow program" unless specified otherwise. I will stick with Edmonds-Karp for simplicity but mention that Dinic is faster for dense graphs.
Wait, I can implement Dinic's just as easily?
Dinic's requires:
BFS for level graph.
DFS for blocking flow.
It's slightly more code. Edmonds-Karp is essentially just BFS + path reconstruction. It's more intuitive for a general request. I will provide Edmonds-Karp.
Let's write the code.
python
class Graph:
def __init__(self, n):
self.n = n
self.adj = [[] for _ in range(n)]
def add_edge(self, u, v, cap):
# Forward edge: index 0 in adj[v] storage is not known yet, but we handle references carefully
# Standard pattern:
# adj[u].append([v, cap, len(adj[v])])
# adj[v].append([u, 0, len(adj[u]) - 1])
pass
Actually, a cleaner way to define edges is a small class or namedtuple, but lists are faster in Python. Lists it is.
Revised plan:
Explain the algorithm (Edmonds-Karp).
Provide Python Code.
Explain how to use it.
Briefly mention complexity.
Let's double check the add_edge logic for undirected graphs?
The problem says "flow network", which is usually directed. If it were undirected, capacity works both ways. Standard implementation handles directed edges. If the user wants undirected, they can call add_edge(u, v, c) and add_edge(v, u, c). I will assume directed edges as per standard definition.
Code check:
Inside the update loop:
path_flow found.
Start at v = sink.
While v != source:
u = parent[v]edge = graph[u][edge_idx]edge[1] -= path_flowrev_edge = graph[v][edge[2]]rev_edge[1] += path_flowv = u
This looks correct.
One detail: What if the graph is huge? Recursion limit? BFS is iterative. The path reconstruction is iterative. Python deque for queue.
Okay, ready to generate.
Here is a complete implementation of the Edmonds-Karp algorithm to find the maximum flow in a flow network.
This algorithm uses Breadth-First Search (BFS) to find the shortest augmenting path from the source to the sink in each step. This guarantees that the algorithm terminates and runs in polynomial time (O(VE2)).
Python Implementation
python
How it Works
Residual Graph: The algorithm doesn't just modify the original capacities; it maintains a "residual graph" (Gf). If you send 10 units of flow down a pipe with capacity 16, the residual capacity forward is 6, but you create a "virtual" backward pipe with capacity 10. This allows the algorithm to "undo" decisions later if it finds a better path.
BFS (Level Graph): Unlike the standard Ford-Fulkerson method (which might use DFS and can be slow), Edmonds-Karp uses BFS. This ensures we always find the shortest path (in terms of edges) from Source to Sink.
Bottleneck: Once a path is found, we determine the "bottleneck" — the pipe in that path with the least remaining space. We push that amount of flow through the entire path.
Iteration: We repeat this process until the BFS can no longer reach the Sink (meaning the network is "saturated" or "cut").
Complexity
Time Complexity:O(VE2), where V is the number of vertices and E is the number of edges. This is efficient enough for medium-sized networks.
Space Complexity:O( to store the graph.
V=
500,E=
20000
100⋅108/4
from collections import deque
class Edge:
def __init__(self, v, flow, capacity, rev):
self.v = v # Target vertex
self.flow = flow # Current flow
self.capacity = capacity # Maximum capacity
self.rev = rev # Index of the reverse edge in the target vertex's list
class MaxFlow:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.graph = [[] for _ in range(num_vertices)]
def add_edge(self, u, v, capacity):
"""
Adds a directed edge from u to v with given capacity.
Also adds a residual edge from v to u with 0 capacity.
"""
# Forward edge: index 0 in v's list currently (before appending)
# But we calculate indices based on current sizes
# Edge u -> v
forward_edge = Edge(v, 0, capacity, len(self.graph[v]))
# Edge v -> u (Residual)
backward_edge = Edge(u, 0, 0, len(self.graph[u]))
self.graph[u].append(forward_edge)
self.graph[v].append(backward_edge)
def bfs(self, source, sink, parent):
"""
Returns True if there is a path from source to sink in residual graph.
Also fills the parent array to store the path.
"""
# Mark all vertices as not visited
visited = [False] * self.num_vertices
queue = deque()
queue.append(source)
visited[source] = True
# Standard BFS loop
while queue:
u = queue.popleft()
# Iterate through all edges of vertex u
for i, edge in enumerate(self.graph[u]):
# If the vertex is not visited and has residual capacity > 0
if not visited[edge.v] and edge.capacity > edge.flow:
queue.append(edge.v)
visited[edge.v] = True
parent[edge.v] = (u, i) # Store vertex and edge index
if edge.v == sink:
return True
return False
def get_max_flow(self, source, sink):
"""
Computes the maximum flow from source to sink using Edmonds-Karp algorithm.
"""
max_flow = 0
parent = [None] * self.num_vertices
# Augment the flow while there is a path from source to sink
while self.bfs(source, sink, parent):
# Find the maximum possible flow through the path found by BFS
# (The bottleneck capacity)
path_flow = float('Inf')
s = sink
while s != source:
u, edge_idx = parent[s]
edge = self.graph[u][edge_idx]
path_flow = min(path_flow, edge.capacity - edge.flow)
s = u
# Add the path flow to the total max flow
max_flow += path_flow
# Update residual capacities of the edges and reverse edges
v = sink
while v != source:
u, edge_idx = parent[v]
# Forward edge: decrease available capacity (increase flow)
edge = self.graph[u][edge_idx]
edge.flow += path_flow
# Reverse edge: increase available capacity (allow undoing flow)
# The reverse edge is stored in 'v' at index 'edge.rev'
rev_edge = self.graph[v][edge.rev]
rev_edge.flow -= path_flow # Note: flow is negative for residual or just subtract from capacity logic
# Wait, simpler logic for residual usually:
# Forward Edge: flow += path_flow
# Reverse Edge: flow -= path_flow
v = u
return max_flow
# --- Example Usage ---
if __name__ == "__main__":
# Example from "Introduction to Algorithms" (CLRS) Figure 26.6
# Vertices: 0(s), 1, 2, 3, 4, 5(t)
num_vertices = 6
g = MaxFlow(num_vertices)
# Adding edges (u, v, capacity)
g.add_edge(0, 1, 16)
g.add_edge(0, 2, 13)
g.add_edge(1, 2, 10)
g.add_edge(2, 1, 4) # This is a reverse or cross edge in the original graph
g.add_edge(1, 3, 12)
g.add_edge(2, 4, 14)
g.add_edge(3, 2, 9)
g.add_edge(4, 3, 7)
g.add_edge(3, 5, 20)
g.add_edge(4, 5, 4)
source = 0
sink = 5
print(f"Maximum Flow from {source} to {sink} is: {g.get_max_flow(source, sink)}")