MediumDepth-First SearchBreadth-First SearchUnion FindGraph

Number of Provinces

LeetCode
1 approach, code in all languages

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]
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now