Friend Circles

来源:互联网 发布:爱奇艺网络大电影票房 编辑:程序博客网 时间:2024/05/21 17:55

这是一道leetcode上的题目,题目要求大概是要找出有多少个连通块,
一开始想用些奇技淫巧,后来还是用了DFS暴力解决。
原题如下:
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.

代码如下:

bool a[201]={0};    int findCircleNum(vector<vector<int>>& M) {        if (M.empty()) return 0;        int len= M.size();        int num = 0;        for (int i = 0; i < len; i++) {           if(!a[i]) {num++;                     dfs(i,M);}        }        return num;    }    void dfs(int i, vector<vector<int>>& M) {       if(a[i]) return;        int s = 1;        a[i] = true;        for (int j = 0; j < M.size(); j++) {            if (i != j && M[i][j]) {                dfs(j, M);            }        }        return ;    }