LeetCode 547. 朋友圈

習題地址  https://leetcode-cn.com/problems/friend-circles/ide

班上有 N 名學生。其中有些人是朋友,有些則不是。他們的友誼具備是傳遞性。若是已知 A 是 B 的朋友,B 是 C 的朋友,那麼咱們能夠認爲 A 也是 C 的朋友。所謂的朋友圈,是指全部朋友的集合。spa

給定一個 N * N 的矩陣 M,表示班級中學生之間的朋友關係。若是M[i][j] = 1,表示已知第 i 個和 j 個學生互爲朋友關係,不然爲不知道。你必須輸出全部學生中的已知的朋友圈總數。code

示例 1:blog

輸入: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
輸出: 2 
說明:已知學生0和學生1互爲朋友,他們在一個朋友圈。
第2個學生本身在一個朋友圈。因此返回2。

示例 2:遞歸

輸入: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
輸出: 1
說明:已知學生0和學生1互爲朋友,學生1和學生2互爲朋友,因此學生0和學生2也是朋友,因此他們三個在一個朋友圈,返回1。

注意:ci

  1. N 在[1,200]的範圍內。
  2. 對於全部學生,有M[i][i] = 1。
  3. 若是有M[i][j] = 1,則有M[j][i] = 1。

解答leetcode

並查集常規用法get

 

 1 class UnionFind {
 2 public:
 3     vector<int> father;
 4     UnionFind(int num) {
 5         for (int i = 0; i < num; i++) {
 6             father.push_back(i);    //每一個人都指向本身
 7         }
 8     }
 9     int Find(int n) {
10         //非遞歸版本 
11         /*
12         while (father[n] != n) {
13             n = father[n];
14         }
15         return n;
16         */
17         //遞歸
18         if (father[n] == n)
19             return n;
20         father[n] = Find(father[n]);
21         return father[n] ;
22     }
23     void Union(int a, int b) {
24         int fa = Find(a);
25         int fb = Find(b);
26         father[fb] = fa;
27     }
28 };
29 
30 class Solution {
31 public:
32     int findCircleNum(vector<vector<int>>& M) {
33         int N = M.size();
34         UnionFind UF(N);
35         for(int i =0;i < N;i++){
36             for(int j =0;j<N;j++){
37                 if(M[i][j]){
38                     UF.Union(i,j);
39                 }
40             }
41         }
42         int res = 0;
43         for(int i=0;i < N;i++){
44             if(UF.Find(i) == i)
45                 res++;
46         }
47         return res;
48     }
49 };
View Code
相關文章
相關標籤/搜索