There are n cities, some connected directly. You are given an n × n matrix isConnected where isConnected[i][j] == 1 means city i and city j are directly connected (the matrix is symmetric and the diagonal is 1). A province is a group of cities connected directly or indirectly. Return the total number of provinces.
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] Output: 2 Cities 0 and 1 form one province; city 2 is another.
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] Output: 3 No connections, so three provinces.
- 1 <= n <= 200 - isConnected[i][j] is 0 or 1 - isConnected[i][i] == 1 - isConnected[i][j] == isConnected[j][i]
A province is a connected component — the twist is the graph arrives as an adjacency matrix rather than an edge list. Two standard counts:
DFS/BFS flood. From each unvisited city, walk to every directly-connected city (scan row isConnected[u]), marking the whole province; each fresh start is a new province. Scanning rows makes it O(n²), which is optimal given an n × n matrix.
Union-Find. Union i and j whenever isConnected[i][j] == 1 (only the upper triangle needs checking, since it's symmetric). Start the count at n and subtract one per real merge. Also O(n²) to scan the matrix, with near-constant union cost.
“Is the matrix symmetric?”
Yes, and the diagonal is 1 (each city connects to itself).
“Direct vs indirect connection?”
Indirect still merges them into one province.
Each row of the matrix is a city's neighbour list, so I flood each unvisited city — one flood per province.
Or union-find: union every connected pair and count how many merges happen. Both are O(n²) to read the matrix.
Worked example — isConnected = [[1,1,0],[1,1,0],[0,0,1]]
flood 0 -> reaches 1 (isConnected[0][1]=1) -> province {0,1}
flood 2 -> isolated -> province {2}
answer = 2
Neighbours of u are the columns v with isConnected[u][v] == 1.
Only the upper triangle (j > i) needs checking for union-find.
Reading an n×n matrix already costs n².
| DFS flood | Union-Find | |
|---|---|---|
| Idea | Flood each unvisited city via its row | Union connected pairs, count merges |
| Time | O(n²) | O(n² α) |
| Space | O(n) | O(n) |
Both count provinces in O(n²), dominated by reading the matrix. Full code is in the Approaches selector below.
Key takeaway
A province is a connected component of the matrix graph. Flood each unvisited city (scanning its row), or union every connected pair and count merges. O(n²) time.
for each city: if unvisited: provinces++, dfs(city) # neighbours = row 1s