Graph Theory37 sections · 1633 units
Open in Course

School Dance - Algorithm

(DFS-based matching)

For each boy ii from 11 to nn, call dfs(i)\text{dfs}(i) with a fresh visited array. The DFS tries to match boy ii to some girl jj in his adjacency list. If girl jj is currently unmatched, set match[j] = i and return true.

If jj is matched to boy kk, recursively try to rematch kk to a different girl. If that succeeds, take jj for yourself. Count how many boys successfully match. This count is your answer.

This runs in O(VE)O(VE) time and uses O(V)O(V) space.