![]() |
VOOZH | about |
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.
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.
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.
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.