DFS 사용
class Solution {
static boolean visit[];
public int solution(int n, int[][] computers) {
int answer = 0;
visit = new boolean[n];
for(int i=0; i<n; i++) {
if(visit[i] == false) {
answer++;
DFS(i, computers, n);
}
}
return answer;
} // End of main
static void DFS(int i, int computers[][], int n) {
visit[i] = true;
for(int j=0; j<n; j++) {
if(visit[j] == false && computers[i][j] == 1) {
DFS(j, computers, n);
}
}
} // End of DFS
} // End of class
BFS 사용
import java.util.*;
class Solution {
static boolean visit[];
static Queue<Integer> que = new LinkedList<>();
public int solution(int n, int[][] computers) {
int answer = 0;
visit = new boolean[n];
for(int i=0; i<n; i++) {
if(visit[i] == false) {
BFS(i, computers, n);
answer++;
}
}
return answer;
} // End of main
static void BFS(int i, int computers[][], int n) {
que.offer(i);
visit[i] = true;
while( !que.isEmpty() ) {
int value = que.poll();
for(int j=0; j<n; j++) {
if(visit[j] == false && computers[value][j] == 1) {
visit[j] = true;
que.offer(j);
}
}
}
} // End of BFS
} // End of class