1.解析
題目大意,給定朋友關係矩陣,求解有多少個朋友圈。(A是B的朋友,B是C的朋友,則A和C是朋友,即關係具有傳遞性)
2.分析
這道題如果看表面題意,還是比較難的,我們可以抽象一下。例如,題目中所給的例子:[[1,1,0],[1,1,0],[0,0,1]],轉換題目意思就是,給定3個城鎮,編號爲0-2,編號爲0和1的城鎮之間是連通的,求解有多少條連通路徑。很明顯,這就是並查集的基本運用,比較簡單。
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
int res = 0, n = M[0].size();
vector<int> nums(n);
for (int i = 0; i < n; ++i) nums[i] = i;
for (int i = 1; i < n; ++i){
for (int j = 0; j < i; ++j){
if (M[i][j] == 1){
int a = getRoot(nums, i);
int b = getRoot(nums, j);
if (a != b){
nums[a] = b;
}
}
}
}
for (int i = 0; i < n; ++i)
if (nums[i] == i)
res++;
return res;
}
int getRoot(vector<int>& nums, int root){
int son = root;
while (root != nums[root]) root = nums[root];
while (son != root){ //路徑壓縮
int t = nums[son];
nums[son] = root;
son = t;
}
return root;
}
};