 All Problems
Number of Provinces
medium
union-find
graph
dfs
amazon
google
facebook

There are n cities. Some of them are connected directly. Given an n x n matrix isConnected where isConnected[i][j] = 1 if cities i and j are directly connected, return the total number of provinces (groups of directly or indirectly connected cities).

Example 1:

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2

Example 2:

Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3

Constraints:

  • 1 <= n <= 200
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]
Run to check your code against the sample cases, or submit to run every case