Graph Theory37 sections · 1633 units
Open in Course

LeetCode 547 Number of Provinces - Strategy

Iterating the Matrix

1.1. Initialize DSU with nn nodes, count = n.

2.2. Iterate through the matrix isConnected[i][j].

3.3. If isConnected[i][j] = 1 and find(i) != find(j), union them and decrement count.

4.4. Return count.

Each successful union reduces components by one. Final count is the number of provinces. Time: O(n2α(n))O(n^2 \cdot \alpha(n)) due to matrix traversal. Space: O(n)O(n) for the DSU arrays. You could also solve this with DFS or BFS, but DSU is cleaner here.