Open In App

Maximum Flow Problem in Python

Last Updated : 04 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The maximum flow problem is a classic optimization problem in network theory, where the goal is to determine the maximum possible flow from a source node to a sink node in a flow network. A flow network is represented as a directed graph with each edge having a capacity, which is the maximum amount of flow that can pass through it. The problem finds applications in various fields such as computer networks, logistics, and transportation systems.

Algorithm to Find Maximum Flow in Python

The most commonly used algorithm to solve the maximum flow problem is the Ford-Fulkerson method. This method involves finding augmenting paths in the network and increasing the flow along these paths until no more augmenting paths can be found.

Steps of the Ford-Fulkerson Algorithm:

  1. Initialize flow: Start with zero flow in all edges.
  2. Find augmenting path: Use Depth-First Search (DFS) or Breadth-First Search (BFS) to find a path from the source to the sink such that the capacity along the path is greater than the current flow.
  3. Update flow: Increase the flow along the found path by the minimum residual capacity (bottleneck capacity) of the path.
  4. Repeat: Continue finding augmenting paths and updating flows until no more augmenting paths can be found.

The Edmonds-Karp algorithm is an implementation of the Ford-Fulkerson method using BFS to find the augmenting paths, which ensures the algorithm runs in polynomial time.

Example to Illustrate the Algorithm

Consider the following flow network with source S, sink T, and edges with capacities:

Example
     A (source)
    / \
   /   \
  B     C
  |     |
  D -- E (sink)

The capacities of the edges are:

  • AB = 3
  • AC = 3
  • BD = 2
  • BE = 4
  • CE = 2

Using the Ford-Fulkerson algorithm, we can find the maximum flow from A to E as follows:

  • Iteration 1:
    • Augmenting path: A -> B -> D -> E
    • Flow increased by 2 (minimum capacity of BD and DE)
  • Iteration 2:
    • Augmenting path: A -> C -> E
    • Flow increased by 2 (minimum capacity of CE)
  • Iteration 3:
    • Augmenting path: A -> B -> E
    • Flow increased by 1 (minimum capacity of BE)
  • The final maximum flow is 5, with 2 units flowing through BD and DE, 2 units through CE, and 1 unit through BE.

Implementation in Python

Here's an example implementation of the Ford-Fulkerson algorithm in Python:

Python
from collections import defaultdict

class Graph:
    def __init__(self, graph):
        self.graph = graph  # residual graph
        self.ROW = len(graph)

    def BFS(self, s, t, parent):
        """
        Performs Breadth-First Search to find an augmenting path.

        Args:
            s: Source node.
            t: Sink node.
            parent: Array to store the parent node for each node in the path.

        Returns:
            True if an augmenting path is found, False otherwise.
        """
        visited = [False] * self.ROW
        queue = []
        queue.append(s)
        visited[s] = True

        while queue:
            u = queue.pop(0)
            for ind, val in enumerate(self.graph[u]):
                if visited[ind] == False and val > 0:
                    queue.append(ind)
                    visited[ind] = True
                    parent[ind] = u

        return True if visited[t] else False

    def FordFulkerson(self, source, sink):
        """
        Implements the Ford-Fulkerson algorithm to find the maximum flow.

        Args:
            source: Source node.
            sink: Sink node.

        Returns:
            The maximum flow value.
        """
        parent = [-1] * self.ROW
        max_flow = 0

        while self.BFS(source, sink, parent):
            path_flow = float("Inf")
            s = sink
            while s != source:
                path_flow = min(path_flow, self.graph[parent[s]][s])
                s = parent[s]

            max_flow += path_flow

            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 graph
graph = [[0, 16, 13, 0, 0, 0],
        [0, 0, 10, 12, 0, 0],
        [0, 4, 0, 0, 14, 0],
        [0, 0, 9, 0, 0, 20],
        [0, 0, 0, 7, 0, 4],
        [0, 0, 0, 0, 0, 0]]

g = Graph(graph)

source = 0
sink = 5

max_flow = g.FordFulkerson(source, sink)

print("Maximum flow:", max_flow)

Output
The maximum possible flow is 20

Related Post:


Next Article
Article Tags :
Practice Tags :

Similar Reads