Number of Provinces
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: ann × nmatrix ofncities;isConnected[i][j]is1when citiesiandjare connected directly and0when 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]
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more union-find problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.