Number of Provinces - Problem
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
Input & Output
Example 1 — Two Separate Provinces
$
Input:
isConnected = [[1,1,0],[1,1,0],[0,0,1]]
›
Output:
2
💡 Note:
Cities 0 and 1 are connected (province 1). City 2 is isolated (province 2). Total: 2 provinces.
Example 2 — All Connected
$
Input:
isConnected = [[1,0,0],[0,1,0],[0,0,1]]
›
Output:
3
💡 Note:
No connections between cities. Each city is its own province: 0, 1, 2. Total: 3 provinces.
Example 3 — Chain Connection
$
Input:
isConnected = [[1,1,0],[1,1,1],[0,1,1]]
›
Output:
1
💡 Note:
City 0↔1, City 1↔2, so all cities are in one connected province. Total: 1 province.
Constraints
- 1 ≤ n ≤ 200
- n == isConnected.length
- n == isConnected[i].length
- isConnected[i][j] is 1 or 0
- isConnected[i][i] == 1
- isConnected[i][j] == isConnected[j][i]
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Adjacency matrix showing city connections
2
Find Components
Group connected cities using DFS/BFS
3
Count Provinces
Number of separate connected components
Key Takeaway
🎯 Key Insight: Count connected components by starting DFS from each unvisited city
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code