547. 朋友圈

 1 class Solution 
 2 {
 3     vector<int> p;
 4 
 5     int find(int x)
 6     {
 7         if(p[x] != x) p[x] = find(p[x]);
 8         return p[x];
 9     }
10 public:
11     int findCircleNum(vectorint>>& M) 
12     {
13         int n = M.size();
14         for(int i = 0;i < n;i ++) p.push_back(i);
15 
16         int res = n;
17         for(int i = 0;i < n;i ++)
18         {
19             for(int j = 0;j < i;j ++)
20             {
21                 if(M[i][j] == 0) continue;
22                 if(find(i) != find(j))
23                 {
24                     p[find(i)] = find(j);
25                     res --;
26                 }
27             }
28         }
29         return res;
30     }
31 };

 

你可能感兴趣的:(547. 朋友圈)