Problem
There are n cities, and isConnected[i][j] is 1 when city i is directly connected to city j. A province is a group of cities that are connected directly or indirectly. Return the number of provinces.
Original: LeetCode 547: Number of Provinces.
Examples
Example 1
`isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]``2`Example 2
`isConnected = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]``3`Constraints
1 <= n <= 200n == isConnected.lengthn == isConnected[i].lengthisConnected[i][j]is1or0.isConnected[i][i] == 1isConnected[i][j] == isConnected[j][i]
Hints
Hint 1
The matrix is symmetric, and the diagonal is 1. This is Number of Islands on a graph given as an adjacency matrix, not as a grid.
Hint 2
Connected components: DFS, BFS, or union-find.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. You must inspect every matrix entry in the worst case, so the work is in visiting each city once.
Optimal. For every unvisited city, increment the answer and DFS through all cities j where isConnected[i][j] is 1.
Alternative. Union-find: for i < j, union i and j when they are connected, then count unique parents.
Complexity
- Time
- O(n²)
O(n²) time, because the adjacency matrix has n² entries, and O(n) extra space.
- Space
- O(n)
Code
def find_circle_num(is_connected: list[list[int]]) -> int:
n = len(is_connected)
seen = [False] * n
def dfs(i: int) -> None:
seen[i] = True
for j in range(n):
if is_connected[i][j] == 1 and not seen[j]:
dfs(j)
count = 0
for i in range(n):
if not seen[i]:
count += 1
dfs(i)
return count
if __name__ == "__main__":
assert find_circle_num([[1, 1, 0], [1, 1, 0], [0, 0, 1]]) == 2
assert find_circle_num([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == 3
print("ok")public class NumberOfProvinces {
static int findCircleNum(int[][] isConnected) {
int n = isConnected.length, count = 0;
boolean[] seen = new boolean[n];
for (int i = 0; i < n; i++) {
if (!seen[i]) {
count++;
dfs(isConnected, seen, i);
}
}
return count;
}
static void dfs(int[][] g, boolean[] seen, int i) {
seen[i] = true;
for (int j = 0; j < g.length; j++) if (g[i][j] == 1 && !seen[j]) dfs(g, seen, j);
}
public static void main(String[] args) {
if (findCircleNum(new int[][] {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}) != 2) throw new AssertionError();
if (findCircleNum(new int[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}) != 3) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: [[1,1,0],[1,1,0],[0,0,1]] is two provinces, and [[1,0,0],[0,1,0],[0,0,1]] is three.
- A fully connected matrix is one province.
Follow-ups
- If the input were a sparse edge list, union-find or adjacency-list DFS would be linear in the number of edges.
Interview script
"This is connected components on an adjacency matrix. I start a DFS from every unvisited city and increment the province count once per new start."
Source: LeetCode 547: Number of Provinces
Dependencies and trees
Sources (1)
- LeetCode 547: Number of Provincesleetcode.com