VOOZH about

URL: https://www.geeksforgeeks.org/dsa/hopcroft-karp-algorithm-for-maximum-matching-set-2-implementation/

⇱ Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)

Last Updated : 23 Jul, 2025

We strongly recommend to refer below post as a prerequisite.
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)

There are few important things to note before we start implementation. 

  1. We need to find an augmenting path (A path that alternates between matching and not matching edges and has free vertices as starting and ending points).
  2. Once we find the augmenting path, we need to add the found path to the existing Matching. Here adding a path means, making previous matching edges on this path as not-matching and previous not-matching edges as matching.

The idea is to use BFS (Breadth First Search) to find augmenting paths. Since BFS traverses level by level, it is used to divide the graph in layers of matching and not matching edges. A dummy vertex NIL is added that is connected to all vertices on the left side and all vertices on the right side. The following arrays are used to find augmenting paths. Distance to NIL is initialized as INF (infinite). If we start from a dummy vertex and come back to it using alternating paths of distinct vertices, then there is an augmenting path.

  1. pairU[]: An array of size m+1 where m is the number of vertices on the left side of the Bipartite Graph. pairU[u] stores paa r of u on the right side if u is matched and NIL otherwise.
  2. pairV[]: An array of size n+1 where n is several vertices on the right side of the Bipartite Graph. pairV[v] stores a pair of v on the left side if v is matched and NIL otherwise.
  3. dist[]: An array of size m+1 where m is several vertices on the left side of the Bipartite Graph. dist[u] is initialized as 0 if u is not matching and INF (infinite) otherwise. dist[] of NIL is also initialized as INF

Once an augmenting path is found, DFS (Depth First Search) is used to add augmenting paths to current matching. DFS simply follows the distance array setup by BFS. It fills values in pairU[u] and pairV[v] if v is next to u in BFS. 

Below is the implementation of above Hopkroft Karp algorithm.


Output
Size of maximum matching is 4

Time Complexity : O(√V x E), where E is the number of Edges and V is the number of vertices.
Auxiliary Space : O(V) as we are using extra space for storing u and v.

The above implementation is mainly adopted from the algorithm provided on Wiki page of Hopcroft Karp algorithm.

Comment
Article Tags:
Article Tags: