Number of Provinces
1 approach, code in every language
Problem description
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]
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Count the Sensor Meshes is our own problem on the technique behind Number of Provinces: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free