Link: https://leetcode.com/problems/number-of-provinces/
Solution:
Topics: DFS, union find
Intuition
This is a kind of annoying variation on the connected components class of problems. The reason why it’s annoying is because the graph is given in a strange form which complicates the graph traversal. On first glance one could think think that the connected components are adjacently connected 1’s but this is not the case.
Each node must be connected to itself…which doesn’t really make sense but this is how the graph is modelled.
For example:
connected to 3
/ |
[1, 0, 1] |
[0, 1, 0] | this is a valid connection,
[1, 0, 1] | the traversal must jump from
\ | city 1 to city 3
connected to 1
There is also a union find solution, which is extremely efficient for relationship graphs…it’s also the only efficient way to find connected components in dynamic graphs (updating relationships). Not a perfect use case here because our graph is static but none the less an interesting approach.
Implementation (DFS)
Implementation (union find)
Visual
Review 1
The easiest solution here is to build an adjacency list and count components. The slightly better solution is to traverse the matrix as-is! This is a more subtle solution but eliminates the need for an adjacency list. The even more subtle solution is to use union find.
Its a tricky one because traversing the matrix is not straight forward.