MediumDepth-First SearchBreadth-First SearchUnion FindGraph

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 <= 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]

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