LeetCode 547 Number of Provinces - Solution

The core idea

Use Union-Find. Initially, each city is its own province.

For each pair of cities (i, j) where isConnected[i][j] = 1, union them.

The number of provinces is the number of distinct roots in the Union-Find structure (count cities where find(i) == i).

Alternatively, count how many times union actually merges two different components.