博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
547. Friend Circles
阅读量:4938 次
发布时间:2019-06-11

本文共 1953 字,大约阅读时间需要 6 分钟。

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: 2Explanation: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: 1Explanation: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.

 

M[0][1]  表示0和1是直接好友关系

M[1][2]  表示1和2是直接好友关系   0,2是间接好友关系  他们是一个朋友圈

求有多少个朋友圈,也就是无向图的连通分量

 

C++:

1 class Solution { 2 public: 3     int findCircleNum(vector
>& M) { 4 int n = M.size() ; 5 int res = 0 ; 6 vector
visit(n , false) ; 7 for(int i = 0 ; i < n ; i++){ 8 if (!visit[i]){ 9 dfs(i,M,visit) ;10 res++ ;11 }12 }13 return res ;14 }15 16 void dfs(int i , vector
> M , vector
& visit){17 visit[i] = true ;18 for(int j = 0 ; j < M.size() ; j++){19 if (M[i][j] == 1 && !visit[j]){20 dfs(j,M,visit) ;21 }22 }23 }24 };

 

转载于:https://www.cnblogs.com/mengchunchen/p/10339574.html

你可能感兴趣的文章
文档流
查看>>
xcode加载静态链接库.a文件总是失败
查看>>
加密签名
查看>>
7.volatile关键字
查看>>
【转载】古典密码
查看>>
python性能优化
查看>>
软件工程的意义
查看>>
如何在Oracle 10g中跟踪SQL
查看>>
android IOC框架学习记录
查看>>
CDOJ 1279 班委选举 每周一题 div2 暴力
查看>>
HDU 5745 La Vie en rose 暴力
查看>>
Day12 线程池、RabbitMQ和SQLAlchemy
查看>>
jQuery中$.each()方法的使用(从业人员项目--添加产品和修改产品,定价时用到了)...
查看>>
《算法导论》第六章----优先级队列(代码实现+部分练习)
查看>>
《Linux/Unix系统编程手册》读书笔记3
查看>>
10·
查看>>
Iframe高度自适应
查看>>
thinkphp-内置标签
查看>>
qt QTableWidget&&QTableView 导出数据到excel
查看>>
二叉树
查看>>