HelloKenLee

Leetcode 547. Friend Circles 解题报告

Posted on By KenLee

题目信息

题目: 547. Friend Circles
难度: Medium
正确率: 48.8%
问题描述:

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

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:

  1. N is in range [1,200].
  2. M[i][i] = 1 for all students.
  3. If M[i][j] = 1, then M[j][i] = 1.

问题分析

  题目的意思是给你一个无向图的NxN邻接矩阵M,表示N个人的朋友关系,如果i和j是朋友关系,M[i][j]和M[j][i]就是1,反之是0。 朋友关系有传递性, A和B是朋友,B和C也是朋友,那么A和C也是属于朋友。 题目希望找出给出的图中有多少个“朋友圈”, 即朋友圈中的人互相是直接或者间接的朋友。

解题思路

  通过题目分析,我们可以发现,题目很简单,就是在一个无向图中找强连通分量(SCC)。直接通过DFS来找,把不同起点的DFS记作不同的SCC。

结果分析

  • 时间复杂度: $ O(N^2) $ 每一个顶点查找相邻顶点的复杂度为$ O(N) $,每一个顶点都需要经历这个过程。
  • 空间复杂度: $ O(N) $ Visited数组
  • 通过时间: 42 ms
  • 击败: 06.06%的提交

源代码

//事实上就是在无向图中找SCC的数量嘛
class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        if(M.size() == 0){
            return 0;
        }
        int unionNum=0;
        vector<int> visited(M.size(), false);
        
        for(int v=0; v<M.size(); ++v){
            if(!visited[v]){
                ++unionNum;
                dfs(v, visited, M);
            }
        }
        return unionNum;
    }
private:
    void dfs(int v, vector<int> &visited, vector<vector<int>>& M){
        for(int i=0;i<M[v].size();++i){
            if(!visited[i] && M[v][i] == 1){
                visited[i]=true;
                dfs(i, visited, M);
            }
        }
    }
};