We strongly recommend to refer below post as a prerequisite.
There are few important things to note before we start implementation.
- 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).
- Once we find alternating path, we need to add the found path to existing Matching. Here adding 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 left side and all vertices on right side. Following arrays are used to find augmenting path. Distance to NIL is initialized as INF (infinite). If we start from dummy vertex and come back to it using alternating path of distinct vertices, then there is an augmenting path.
- pairU: An array of size m+1 where m is number of vertices on left side of Bipartite Graph. pairU[u] stores pair of u on right side if u is matched and NIL otherwise.
- pairV: An array of size n+1 where n is number of vertices on right side of Bipartite Graph. pairV[v] stores pair of v on left side if v is matched and NIL otherwise.
- dist: An array of size m+1 where m is number of vertices on left side of 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 C++ implementation of above Hopkroft Karp algorithm.
Size of maximum matching is 4
The above implementation is mainly adopted from the algorithm provided on Wiki page of Hopcroft Karp algorithm.