问题:
给定一个二维数组,每个元素M[i][j]
代表i和j是否为朋友:是朋友则为1,否则为0
求形成了多少个朋友圈。(朋友的朋友,认为在一个朋友圈)
Example 1: Input: [[1,1,0], [1,1,0], [0,0,1]] Output: 2 Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2. Example 2: Input: [[1,1,0], [1,1,1], [0,1,1]] Output: 1 Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1. Note: N is in range [1,200]. M[i][i] = 1 for all students. If M[i][j] = 1, then M[j][i] = 1.
解法:并查集(Disjoint Set)
遍历二维数组,i:0~size, j:0~i
若为1,则merge两个点 i 和 j
最后,求parent有多少个root
遍历parent,其中 i == parent[i] 的,即为顶点root。
代码参考:
1 class DisjointSet { 2 public: 3 DisjointSet(int n):parent(n), rank(n,0) { 4 for(int i=0; i<n; i++) { 5 parent[i] = i; 6 } 7 } 8 int find(int i) { 9 if(parent[i] != i) { 10 parent[i] = find(parent[i]); 11 } 12 return parent[i]; 13 } 14 bool merge(int x, int y) { 15 int x_root = find(x); 16 int y_root = find(y); 17 if(x_root == y_root) return false; 18 if(rank[x_root] < rank[y_root]) { 19 parent[x_root] = y_root; 20 } else if(rank[x_root] > rank[y_root]) { 21 parent[y_root] = x_root; 22 } else { 23 parent[x_root] = y_root; 24 rank[y_root] ++; 25 } 26 return true; 27 } 28 int getrootsum() { 29 int sum=0; 30 for(int i=0; i<parent.size(); i++) { 31 if(parent[i]==i) sum++; 32 } 33 return sum; 34 } 35 private: 36 vector<int> parent; 37 vector<int> rank; 38 }; 39 40 class Solution { 41 public: 42 int findCircleNum(vector<vector<int>>& M) { 43 DisjointSet DS(M.size()); 44 for(int i=0; i<M.size(); i++) { 45 for(int j=0; j<i; j++) { 46 if(M[i][j]==1) DS.merge(i, j); 47 } 48 } 49 return DS.getrootsum(); 50 } 51 };