https://school.programmers.co.kr/learn/courses/30/lessons/43162



이번 문제는 각 컴퓨터로부터 어떤 컴퓨터와 연결되어 있는지 탐색하여 computer[i][j] = 1이면, 해당 컴퓨터의 visited 값을 true로 하여 false인 컴퓨터의 개수에 따라서 bfs 메서드를 몇 번 수행하는지를 반환하면 된다.
bfs가 아닌, dfs로도 풀 수 있겠지만 필자가 생각하기 편한 bfs로 풀도록 하겠다.
import java.util.*;
class Solution {
static Queue<Integer> q = new LinkedList<>();
static boolean[] visit;
public int solution(int n, int[][] computers) {
visit = new boolean[n];
int answer = 0;
for(int i=0; i<n; i++){
if(visit[i] == false){
bfs(i, computers, n);
answer++;
}
}
return answer;
}
public void bfs(int i, int[][] computers, int n){
q.offer(i);
visit[i] = true;
while(!q.isEmpty()){
int x = q.remove();
for(int nx=0; nx<n; nx++){
if(visit[nx] == false && computers[x][nx] == 1){
visit[nx] = true;
q.add(nx);
}
}
}
}
}
일반적인 bfs 코드와 유사하고 조건식만 바꾸어주면 되는데, 다른 레벨3 문제에 비해서 좀 쉬운편이긴 한거같다..
풀고나서 다름 사람들의 코드도 찾아봤는데, 매개변수를 어떻게 넘겨주고, 어떤 변수를 전역변수로 처리하는지는 정말 사람마다 제각각이다. 가끔은 그런 코드들 중에 어떤 코드가 가장 좋다고 할 수 있는지도 궁금하다..