ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

547. Friend Circles

2020-08-08 17:31:49  阅读:235  来源: 互联网

标签:Circles parent int friends rank students 547 root Friend


问题:

给定一个二维数组,每个元素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 };

 

标签:Circles,parent,int,friends,rank,students,547,root,Friend
来源: https://www.cnblogs.com/habibah-chang/p/13458620.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有