-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork.java
More file actions
45 lines (41 loc) · 1.15 KB
/
Copy pathNetwork.java
File metadata and controls
45 lines (41 loc) · 1.15 KB
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
import java.util.*;
class Solution {
static boolean[] visited;
static List<Integer>[] adjList;
public int solution(int n, int[][] computers) {
adjList = new ArrayList[n];
for(int i = 0; i < n ; i++) {
adjList[i] = new ArrayList<>();
}
for(int i = 0; i < computers.length; i++) {
for(int j = 0; j < computers[i].length; j++) {
if(i != j && computers[i][j] == 1) {
adjList[i].add(j);
}
}
}
visited = new boolean[n];
int answer = 0;
for(int i = 0; i < n; i++) {
if(!visited[i]) {
bfs(i);
answer++;
}
}
return answer;
}
private void bfs(int i) {
Deque<Integer> que = new ArrayDeque<>();
visited[i] = true;
que.offer(i);
while(!que.isEmpty()) {
Integer current = que.poll();
for(Integer next : adjList[current]) {
if(!visited[next]) {
que.offer(next);
visited[next] = true;
}
}
}
}
}