原题链接在这里:https://leetcode.com/problems/friend-circles/description/

题目:

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.

Example 2:

Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation: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.

题解:

Number of Connected Components in an Undirected Graph类似. 可以采用DFS, BFS, Union Find三种方法.

当M[i][j] == 1. 就说明i 和 j是好友. DFS, BFS时标记走过的点即可.

Time Complexity: O(n^2). n = M.length. M上的点最多走两遍.

Space: O(n). 开了visited array标记. 最多用了n层stack.

AC Java:

 class Solution {
public int findCircleNum(int[][] M) {
if(M == null || M.length == 0 || M[0].length == 0){
return 0;
} int len = M.length;
boolean [] visited = new boolean[len];
int res = 0;
for(int i = 0; i<len; i++){
if(!visited[i]){
dfs(M, visited, i);
res++;
}
} return res;
} private void dfs(int [][] M, boolean [] visited, int i){
for(int j = 0; j<M[0].length; j++){
if(!visited[j] && M[i][j]==1){
visited[j] = true;
dfs(M, visited, j);
}
}
}
}

BFS可以选择在出queue的时候更改标记.

Time Complexity: O(n^2). n = M.length.

Space: O(n).

AC Java:

 class Solution {
public int findCircleNum(int[][] M) {
if(M == null || M.length == 0 || M[0].length == 0){
return 0;
} int res = 0;
int len = M.length;
boolean [] visited = new boolean[len];
LinkedList<Integer> que = new LinkedList<Integer>();
for(int i = 0; i<len; i++){
if(!visited[i]){
res++;
que.add(i);
while(!que.isEmpty()){
int cur = que.poll();
visited[cur] = true;
for(int j = 0; j<len; j++){
if(!visited[j] && M[cur][j]==1){
que.add(j);
}
}
}
}
} return res;
}
}

Union Find Methos is to return the count of unions.

Time Complexity: O(n^2logn). find takes O(logn). With path compression and union by weight, amatorize O(1).

Space: O(n).

AC Java:

 class Solution {
public int findCircleNum(int[][] M) {
if(M == null || M.length == 0 || M[0].length == 0){
return 0;
} int n = M.length;
UnionFind uf = new UnionFind(n);
for(int i = 0; i<n; i++){
for(int j = 0; j<i; j++){
if(i!=j && M[i][j] == 1){
if(uf.find(i) != uf.find(j)){
uf.union(i, j);
}
}
}
} return uf.count;
}
} class UnionFind{
int [] parent;
int [] size;
int count; public UnionFind(int n){
this.parent = new int[n];
this.size = new int[n];
this.count = n; for(int i = 0; i<n; i++){
parent[i] = i;
size[i] = 1;
}
} public int find(int i){
while(i != parent[i]){
parent[i] = parent[parent[i]];
i = parent[i];
} return parent[i];
} public void union(int i, int j){
int x = find(i);
int y = find(j); if(size[x] > size[y]){
parent[y] = x;
size[x] += size[y];
}else{
parent[x] = y;
size[y] += size[x];
} this.count--;
}
}

类似The Earliest Moment When Everyone Become Friends.

LeetCode Friend Circles的更多相关文章

  1. [LeetCode] Friend Circles 朋友圈

    There are N students in a class. Some of them are friends, while some are not. Their friendship is t ...

  2. Leetcode之深度优先搜索(DFS)专题-547. 朋友圈(Friend Circles)

    Leetcode之深度优先搜索(DFS)专题-547. 朋友圈(Friend Circles) 深度优先搜索的解题详细介绍,点击 班上有 N 名学生.其中有些人是朋友,有些则不是.他们的友谊具有是传递 ...

  3. [LeetCode] 547. Friend Circles 朋友圈

    There are N students in a class. Some of them are friends, while some are not. Their friendship is t ...

  4. LeetCode 547. Friend Circles 朋友圈(C++/Java)

    题目: https://leetcode.com/problems/friend-circles/ There are N students in a class. Some of them are ...

  5. 【LeetCode】547. Friend Circles 解题报告(Python & Java & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  6. 【LeetCode Weekly Contest 26 Q3】Friend Circles

    [题目链接]:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/friend-circles/ [题意] 告诉你任意两个 ...

  7. [LeetCode]547. Friend Circles朋友圈数量--不相邻子图问题

    /* 思路就是遍历所有人,对于每一个人,寻找他的好友,找到好友后再找这个好友的好友 ,这样深度优先遍历下去,设置一个flag记录是否已经遍历了这个人. 其实dfs真正有用的是flag这个变量,因为如果 ...

  8. [LeetCode] Number of Islands II 岛屿的数量之二

    A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...

  9. leetcode bugfree note

    463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...

随机推荐

  1. python爬虫之下载京东页面图片

    import requests from bs4 import BeautifulSoup import time import re t = 0 #用于给图片命名 for i in range(10 ...

  2. 11.深入理解读写锁ReentrantReadWriteLock

    protected final int tryAcquireShared(int unused) { /* * Walkthrough: * 1. If write lock held by anot ...

  3. iptables详解(7):iptables扩展之udp扩展与icmp扩展

    前文中总结了iptables的tcp扩展模块,此处,我们来总结一下另外两个跟协议有关的常用的扩展模块,udp扩展与icmp扩展. udp扩展 我们先来说说udp扩展模块,这个扩展模块中能用的匹配条件比 ...

  4. Diff Two Arrays

    比较两个数组,然后返回一个新数组,该数组的元素为两个给定数组中所有独有的数组元素.换言之,返回两个数组的差异. 这是一些对你有帮助的资源: Comparison Operators Array.sli ...

  5. C++高级编程1 C++速成

    C++高级编程1 C++速成 1.常用的预处理指令 #include [file] #define key value 这个是在C中经常使用的,定义常量数值,用于字符串替换的工作. #ifndef k ...

  6. sql中exists,Intersect ,union 与union All的用法

    熟练使用SQL Server中的各种用法会给查询带来很多方便.今天就介绍一下EXCEPT和INTERSECT.注意此语法仅在SQL Server 2005及以上版本支持. EXCEPT是指在第一个集合 ...

  7. RabbitMQ(5) 事务&生产者确认

    事务&生产者确认 一般情况下,生产者将消息发送后,继续进行别的业务逻辑处理.消息从生产者发送后,可能由于网络原因丢失,也可能因为RabbitMQ服务端奔溃未被处理...总之,对于 消息是否安全 ...

  8. springcloud- FeginClient 调用统一拦截添加请求头 RequestInterceptor ,被调用服务获取请求头

    使用场景: 在springcloud中通过Fegin调用远端RestApi的时候,经常需要传递一些参数信息到被调用服务中去,比如从A服务调用B服务的时候, 需要将当前用户信息传递到B调用的服务中去,我 ...

  9. Linux真随机数的生成

    今天看<白帽子讲WEB安全>一书,看到笔者谈到Linux如何实现真随机数生成,感觉非常有用,记录下来 #include<iostream> using namespace st ...

  10. flash cc新建swc文件