-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
44 lines (40 loc) · 1.08 KB
/
Solution.java
File metadata and controls
44 lines (40 loc) · 1.08 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
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
static boolean[] visited;
public static void main(String[] args) {
int n = 3;
int[][] computers = {
{1,1,0}
,{1,1,0}
,{0,0,1}
};
System.out.println(solution(n, computers));
}
public static int solution(int n, int[][] computers){
visited = new boolean[n];
int answer = 0;
for(int i=0; i<n; i++){
if(!visited[i]) {
check(i, computers);
answer++;
}
}
return answer;
}
public static void check(int c, int[][] computers){
Queue<Integer> q = new LinkedList<>();
visited[c] = true;
q.add(c);
while(!q.isEmpty()){
int com = q.poll();
for(int i=0; i<computers.length; i++){
if(i == com) continue;
if(computers[com][i] == 1 && !visited[i]){
visited[i] = true;
q.add(i);
}
}
}
}
}