-
Notifications
You must be signed in to change notification settings - Fork 0
/
FriendCircles.java
70 lines (63 loc) · 1.85 KB
/
FriendCircles.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
/**
* @author Shogo Akiyama
* Solved on 04/27/2019
*
* 547. Friend Circles
* https://leetcode.com/problems/friend-circles/
* Difficulty: Medium
*
* To run the code in LeetCode, take the codes from the following(s):
* - int findCircleNum(int[][] M) method
* - Node class.
*
* Runtime: 67 ms, faster than 5.13% of Java online submissions for Friend Circles.
* Memory Usage: 45.3 MB, less than 33.56% of Java online submissions for Friend Circles.
*
*/
public class FriendCircles {
public int findCircleNum(int[][] M) {
Map<Integer, Node> map = new HashMap<Integer, Node>();
Set<Node> toVisit = new HashSet<Node>();
for(int i=0; i<M.length; i++){
map.put(i, new Node(i));
toVisit.add(map.get(i));
}
for(int i=0; i<M.length; i++){
for(int j=i+1; j<M.length; j++){
if(M[i][j] == 1){
map.get(i).neighbors.add(map.get(j));
map.get(j).neighbors.add(map.get(i));
}
}
}
int count=0;
while(!toVisit.isEmpty()){
count++;
Stack<Node> stack = new Stack<Node>();
stack.push(toVisit.iterator().next());
while(!stack.isEmpty()){
Node curr = stack.pop();
toVisit.remove(curr);
for(Node n: curr.neighbors){
if(toVisit.contains(n)){
stack.push(n);
}
}
}
}
return count;
}
class Node {
int index;
Set<Node> neighbors;
Node(int i){
index = i;
neighbors = new HashSet<Node>();
}
}
}