lc 朋友圈

链接:https://leetcode-cn.com/problems/friend-circles/

代码:

class Solution {
public:
    void solve(vector<vector<int>>& M, int * vis, int start) {
        if(vis[start]) return;
        cout << "start " << start << endl;
        vis[start] = 1;
        int n = M.size();
        for(int i = 0; i < n; i++) {
            if(!vis[i] && 1 == M[start][i]) {
                solve(M, vis, i);
            }
        }
    }
    int findCircleNum(vector<vector<int>>& M) {
        int cnt = 0;
        int n = M.size();
        if(n == 0) return 0;
        int vis[250] = {0};
        for(int i = 0;i < n; i++) {
            for(int j = 0; j < n; j++) {
                if((!vis[i] || !vis[j]) && 1 == M[i][j]) {
                    if(!vis[i] && !vis[j]) {solve(M, vis, i); solve(M, vis, j);}
                    else if(!vis[i]) {solve(M, vis, i);}
                    else {solve(M, vis, j);}
                    cnt++;
                }
            }
        }
        return cnt;
    }
};
View Code

思路:深搜将所有连通的朋友标记一下,再跑遍所有点取“代表”的个数。并查集更好一点。

posted on 2020-05-23 00:04  FriskyPuppy  阅读(188)  评论(0编辑  收藏  举报

导航