oneby7

Graphs Traversing a graph

452. Number of Provinces

Medium

There are n cities, numbered from 0 to n - 1. You are given an n × n matrix isConnected. The value isConnected[i][j] is 1 when cities i and j are directly connected, and 0 when they are not. A connection works both ways, so isConnected[i][j] equals isConnected[j][i]. Every city counts as connected to itself, so isConnected[i][i] is 1.

A province is a group of cities in which every city can reach every other one through a chain of direct connections, and that no connection joins to a city outside the group. A city with no connections is a province on its own.

Return the number of provinces.

Example 1

012345

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

Output: 3

Explanation: Cities 0, 3 and 5 form one province. Cities 0 and 5 are not directly connected, but both are connected to city 3. Cities 1 and 4 form the second province, and city 2 is the third.

Example 2

012

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

Output: 3

Explanation: No two cities are connected, so each city is a province on its own.

Example 3

0123

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

Output: 1

Explanation: City 0 is connected to city 2, city 2 to city 1, and city 1 to city 3. So city 0 reaches city 3 through cities 2 and 1, and all four cities are one province.

Check your understanding

Work out the answer for this input before you write any code.

isConnected = [[1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1]]

Constraints

  • n == isConnected.length == isConnected[i].length
  • 1 ≤ n ≤ 1000
  • isConnected[i][j] is 0 or 1.
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.