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; }};
- 【LeetCode】547. Friend Circles
- leetcode 547. Friend Circles
- leetcode 547. Friend Circles
- 547. Friend Circles
- leetcode-547. Friend Circles
- 547. Friend Circles
- LeetCode 547. Friend Circles
- 547. Friend Circles
- 547. Friend Circles
- #leetcode#547. Friend Circles
- No.547. Friend Circles
- leetcode 547. Friend Circles
- 547. Friend Circles
- LeetCode 547. Friend Circles
- Leetcode 547. Friend Circles
- [leetcode]547. Friend Circles
- [LeetCode]547. Friend Circles
- leetcode 547. Friend Circles
- 简单的Mybatis
- 【Java】关于Map解析List<Map<String, String>>的心得
- 1.if与switch 2.利用for嵌套--倒立三角3.循环与无限循环
- 1023. 组个最小数 (20)-----Python
- CentOS-7.2下配置邮件服务
- 547. Friend Circles
- 程序员国庆加班调查:你是放假,还是被加班了?(内附加班费算法,最少可拿1711元)
- Linux 与 Linux Windows 文件共享
- 每天学写redis命令(2)
- 趣图 | 实习生提出了一个新功能
- 浅析指针与const
- Bootstrap Typeahead 组件
- Recyclerview的初步规范操作
- 五、(二)索引规约