547. Friend Circles

来源:互联网 发布:海马玩mac版怎么安装 编辑:程序博客网 时间:2024/06/03 17:18

547. Friend Circles

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.

分析:
这是一道深度优先的题目。题目意思已经很清楚了,就是找朋友圈。因此我们就对每一个人做一遍深度优先搜索,如果某人属于一个朋友圈,那么我们就将对应的数组置为true,以后再遇到true的人时就不需要对他进行深度优先搜索了。

class Solution {public:    int findCircleNum(vector<vector<int>>& M) {        if (M.empty()) return 0;        int size = M.size();        vector<bool> visited(size, false);        int groups = 0;        for (int index = 0; index < visited.size(); index++) {            groups += dfs(index, M, visited) > 0;        }        return groups;    }private:    int dfs(int index, vector<vector<int>>& M, vector<bool>& visited) {        if (visited[index]) return 0;        int num = 1;        visited[index] = true;        for (int col = 0; col < visited.size(); col++) {            if (index != col && M[index][col]) {                num += dfs(col, M, visited);            }        }        return num;    }};
原创粉丝点击