Number of Provinces

Medium#547

There are n cities and a square matrix isConnected: isConnected[i][j] is 1 when cities i and j are directly connected and 0 when they are not. A province is a group of cities that reach each other directly or through other cities. Count the provinces. Our example: [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1] → 2.

input
isConnected: an n × n matrix of n cities; isConnected[i][j] is 1 when cities i and j are connected directly and 0 when they are not.
returns
The number of provinces: groups of cities that reach each other directly or through other cities.
constraints
  • n = isConnected.length = isConnected[i].length, 1 ≤ n ≤ 100
  • isConnected[i][j] is 0 or 1
  • isConnected[i][i] = 1
  • isConnected[i][j] = isConnected[j][i]
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} isConnected
 * @return {number}
 */
function findCircleNum(isConnected) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more union-find problems

Pattern “Union-Find” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.