네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
static boolean visited[];
public int solution(int n, int[][] computers) {
int cnt = 0;
visited = new boolean[n];
Arrays.fill(visited, false);
//visited배열을 돌며 네트워크를 찾는다.
for (int i = 0; i < n; i++) {
if(!visited[i]){
bfs(i, n, computers);
cnt++;
}
}
return cnt;
}
//현재 컴퓨터 번호를 받아 이어진 컴퓨터를 체크
public void bfs(int v, int n, int[][] computers) {
Queue<Integer> q = new LinkedList<>();
q.add(v);
visited[v] = true;
while(!q.isEmpty()){
int curComputer = q.poll();
//루프를 돌며 computers에 연결된 컴퓨터들 방문
for (int i = 0; i < n; i++) {
//방문하지 않은 컴퓨터면 방문
if(computers[curComputer][i] == 1&& !visited[i]){
//방문한 컴퓨터 체크, 큐에 넣어주기
visited[i] = true;
q.add(i);
}
}
}
}
}