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
Province Detection: From Matrix to Connected GroupsAdjacency Matrix[1,1,0][1,1,0][0,0,1]Input012Connected CitiesResult2Province 1: {0,1}Province 2: {2}ProvincesDFS finds 2 separate connected components
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
Asked in
Amazon 45 Facebook 32 Google 28 Microsoft 22
67.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen