네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
BFS + 총 연결요소 수 구하기 문제다
visited
배열로 방문여부를 저장하고, 아직 방문하지 않은 노드에 대해서 bfs를 구현하면 된다
import java.util.*;
class Solution {
public int solution(int n, int[][] computers) {
int answer = 0;
int[] visited = new int[computers.length];
for (int i = 0; i < computers.length; i++) {
if (visited[i] == 0) {
visited = bfs(i, computers, visited);
answer += 1;
}
}
return answer;
}
private int[] bfs(int visiting, int[][] computers, int[] visited) {
List<Integer> queue = new ArrayList<>();
visited[visiting] = 1;
queue.add(visiting);
while (queue.size() >= 1) {
int x = queue.get(0);
queue.remove(0);
for (int i = 0; i < computers[x].length; i++) {
if (computers[x][i] == 1 && visited[i] == 0) {
queue.add(i);
visited[i] = 1;
}
}
}
return visited;
}
}
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges