Статья пока доступна только на английском.
Problem Description
There are n cities, some of which are connected.
If city a is directly connected to city b, and city b is directly connected to city c, then cities a and c
are connected indirectly.
A province is a group of directly or indirectly connected cities.
You are given an n x n matrix isConnected, where isConnected[i][j] = 1 if the i-th city and the j-th city are directly
connected, and isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
Constraints
- The matrix size
nis an integer in the range from1to200 - The matrix contains only
1and0 isConnected[i][j] == isConnected[j][i]
Examples
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Answer: 2
Solution
There are quite a few solutions to this problem, and all of them are fairly involved. But it becomes easy if you know how
the DisjointSet data structure (also known as UnionFind) works.
You can read about the implementation of DisjointSet in detail in this post.
Once we have the data structure implemented, the problem becomes very easy.
The algorithm:
- Create an instance of
DisjointSet. - Define a variable
numberOfProvincesinitially equal ton. We'll decrement it as we merge cities into provinces. - The main diagonal of
isConnectedrepresents each city's connection to itself, so we can skip it. We also don't need to check the whole matrix, sinceisConnected[i][j] == isConnected[j][i], so we only go over the elements above the main diagonal. For that, we run nested loops overiandj, starting fromi = 0andj = i + 1. - If two cities are connected (
isConnected[i][j] == 1) and they are not in the same set yet, we merge citiesiandjinto one province with theunionmethod and decrementnumberOfProvinces.
After going over the matrix, numberOfProvinces holds the resulting number of provinces.
class DisjointSet {
readonly nodes: number[];
constructor(size: number) {
this.nodes = new Array(size);
for (let i = 0; i < size; i++) {
this.nodes[i] = i;
}
}
find(node: number): number {
return this.nodes[node];
}
union(x: number, y: number): void {
const rootX = this.find(x);
const rootY = this.find(y);
if (rootX !== rootY) {
for (let i = 0; i < this.nodes.length; i++) {
if (this.nodes[i] === rootY) {
this.nodes[i] = rootX;
}
}
}
}
}
export const findCircleNum = (isConnected: number[][]): number => {
const n = isConnected.length;
const disjointSet = new DisjointSet(n);
let numberOfProvinces = n;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (isConnected[i][j] == 1 && disjointSet.find(i) != disjointSet.find(j)) {
numberOfProvinces -= 1;
disjointSet.union(i, j);
}
}
}
return numberOfProvinces;
};Complexity Analysis
Time Complexity
- Traversing the matrix takes
O(n2) - A
findcall takesO(n) - A
unioncall takesO(n)
The overall time complexity is O(n2).
Space Complexity
O(n) to store the state of the DisjointSet structure.