codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

57 / 65 topics
54Network Flow Problems55Ford-Fulkerson Method56Edmonds-Karp Algorithm57Dinic's Algorithm
Tutorials/Data Structures & Algorithms/Dinic's Algorithm
🧮Data Structures & Algorithms

Dinic's Algorithm

Updated 2026-04-20
3 min read

Dinic's Algorithm

Introduction

Dinic's algorithm is a powerful method for computing the maximum flow in a flow network, which is an important problem in graph theory and has numerous applications in various fields such as transportation networks, computer science, and operations research. The algorithm was developed by Edmonds and Karp in 1972 and later improved by Dinic in 1970. It is particularly efficient for large networks due to its layered structure and blocking flow technique.

Overview

Dinic's algorithm operates on a directed graph with capacities on the edges, where each edge has a non-negative capacity representing the maximum amount of flow that can pass through it. The goal is to find the maximum flow from a source node \( s \) to a sink node \( t \).

The key idea behind Dinic's algorithm is to decompose the network into layers and repeatedly find blocking flows in these layers until no more flow can be pushed. A blocking flow is a flow that saturates at least one path from the source to the sink.

Steps of Dinic's Algorithm

  1. Level Graph Construction:

    • Perform a Breadth-First Search (BFS) starting from the source node \( s \). This BFS constructs a level graph where each node has a level indicating its distance from the source.
    • If the sink node \( t \) is not reachable from the source, then there is no flow and the algorithm terminates.
  2. Blocking Flow Construction:

    • Perform Depth-First Search (DFS) on the level graph to find augmenting paths from the source to the sink.
    • For each path found, push the maximum possible flow along that path until it becomes saturated or no more flow can be pushed.
    • Repeat this step until no more augmenting paths can be found in the current level graph.
  3. Repeat:

    • If a blocking flow was found in the previous step, repeat the process by constructing a new level graph and finding a new blocking flow.
    • Continue this process until no more blocking flows can be found, at which point the maximum flow has been achieved.

Implementation

Below is a Python implementation of Dinic's algorithm. This code includes detailed comments to help you understand each step.

from collections import deque

class Edge:
    def __init__(self, v, cap, rev):
        self.v = v  # Target vertex
        self.cap = cap  # Capacity of the edge
        self.rev = rev  # Index of the reverse edge in the adjacency list

def bfs(graph, s, level):
    """
    Perform BFS to construct the level graph.
    """
    queue = deque([s])
    level[s] = 0
    while queue:
        u = queue.popleft()
        for e in graph[u]:
            if e.cap > 0 and level[e.v] < 0:  # If there is residual capacity and not visited
                level[e.v] = level[u] + 1
                queue.append(e.v)
    return level[t] >= 0

def dfs(graph, u, t, f, level):
    """
    Perform DFS to find a blocking flow.
    """
    if u == t:
        return f
    for e in graph[u]:
        if e.cap > 0 and level[e.v] == level[u] + 1:  # If there is residual capacity and the next node is at the correct level
            d = dfs(graph, e.v, t, min(f, e.cap), level)
            if d > 0:
                e.cap -= d
                graph[e.v][e.rev].cap += d
                return d
    level[u] = -1  # Mark as visited
    return 0

def dinic(graph, s, t):
    """
    Main function to compute the maximum flow using Dinic's algorithm.
    """
    n = len(graph)
    max_flow = 0
    while True:
        level = [-1] * n
        if not bfs(graph, s, level):  # Construct the level graph
            break
        f = dfs(graph, s, t, float('inf'), level)  # Find a blocking flow
        while f > 0:
            max_flow += f
            f = dfs(graph, s, t, float('inf'), level)
    return max_flow

# Example usage
n = 6  # Number of nodes
s = 0  # Source node
t = n - 1  # Sink node

# Initialize the graph as an adjacency list
graph = [[] for _ in range(n)]

# Add edges with capacities and reverse edges
def add_edge(u, v, cap):
    graph[u].append(Edge(v, cap, len(graph[v])))
    graph[v].append(Edge(u, 0, len(graph[u]) - 1))

add_edge(0, 1, 16)
add_edge(0, 2, 13)
add_edge(1, 2, 10)
add_edge(1, 3, 12)
add_edge(2, 1, 4)
add_edge(2, 4, 14)
add_edge(3, 2, 9)
add_edge(3, 5, 20)
add_edge(4, 3, 7)
add_edge(4, 5, 4)

# Compute the maximum flow
max_flow = dinic(graph, s, t)
print(f"Maximum Flow from {s} to {t}: {max_flow}")

Explanation of the Code

  1. Edge Class: Represents an edge in the graph with a target vertex v, capacity cap, and index rev for the reverse edge.
  2. bfs Function: Constructs the level graph using BFS. It assigns levels to nodes based on their distance from the source.
  3. dfs Function: Finds augmenting paths using DFS. It pushes flow along these paths until no more flow can be pushed or the path becomes saturated.
  4. dinic Function: Main function that repeatedly constructs level graphs and finds blocking flows until no more flow can be pushed.
  5. Example Usage: Sets up a sample graph and computes the maximum flow from the source to the sink.

Best Practices

  • Edge Capacity Management: Always ensure that reverse edges are correctly managed to maintain the residual capacities during the algorithm execution.
  • Graph Initialization: Properly initialize the graph as an adjacency list with appropriate edge structures.
  • Complexity Considerations: Dinic's algorithm has a time complexity of \( O(V^2E) \), which is efficient for large networks compared to other methods like Ford-Fulkerson.

Conclusion

Dinic's algorithm is a robust and efficient method for solving the maximum flow problem. Its layered structure and blocking flow technique make it well-suited for handling large-scale network flow problems. By understanding the underlying concepts and implementing the algorithm correctly, you can effectively solve complex network flow scenarios in various applications.


PreviousEdmonds-Karp AlgorithmNext Amortized Analysis Basics

Recommended Gear

Edmonds-Karp AlgorithmAmortized Analysis Basics