並查集系列:547 Number of Provinces
技術標籤:LeetCodeC++c++leetcode演算法
Number of Provinces
There are n
cities. Some of them are connected, while some are not. If city a
is connected directly with city b
, and city b
is connected directly with city c
, then city a
is connected indirectly with city c
.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n
matrix isConnected
where isConnected[i][j] = 1
if the ith
city and the jth
city are directly connected, and isConnected[i][j] = 0
otherwise.
Return the total number of provinces.
Example 1:
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Example 2:
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] Output: 3
Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j]
is1
or0
.isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
並查集:
這是一道明顯到不能再明顯的並查集的題目。
有 n 個城市,其中一些彼此相連,另一些沒有相連。如果城市 a 與城市 b 直接相連,且城市 b 與城市 c 直接相連,那麼城市 a 與城市 c 間接相連。
省份是一組直接或間接相連的城市,組內不含其他沒有相連的城市。
使用鄰接矩陣來儲存無向圖。
我的程式碼中用類實現了並查集的合併和查詢操作,查詢操作完成了路徑壓縮。
class DSU
{
private:
int n;
vector<long> f;
public:
DSU(int N){
n = N;
f.resize(n, 1);
for(int i=0; i<n; i++)
f[i] = i;
}
int find(int x){
if(x != f[x])
f[x] = find(f[x]);
return f[x];
}
void unionset(int x, int y){
x = find(x);
y = find(y);
if(x == y)
return;
f[x] = y;
}
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
DSU dsu(n);
set<int> s;
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++)
if(isConnected[i][j])
dsu.unionset(i, j);
}
for(int i=0; i<n; i++)
s.insert(dsu.find(i));
return s.size();
}
};