There are n cities, some of which are directly connected to one another. A province is a group of cities that are connected either directly or indirectly, with no city outside the group belonging to it.
You are given an n x n matrix isConnected, where isConnected[i][j] = 1 means city i and city j are directly connected and isConnected[i][j] = 0 means they are not. Note that the matrix is symmetric and every city is connected to itself.
Return the total number of provinces.
Example 1
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Cities 0 and 1 are connected, forming one province, while city 2 stands alone as a second province.
Example 2
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
No two distinct cities are connected, so each city is its own province.
Constraints
1 <= n <= 200n == isConnected.lengthn == isConnected[i].lengthisConnected[i][j] is 1 or 0.isConnected[i][i] == 1isConnected[i][j] == isConnected[j][i]See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI