알고리즘 문제 풀이를 블로그에 올리는 이유는 풀이, 코드를 기록하기 위함이니
앞으로 문제를 다 긁어오기보다 링크만 두고 풀이가 잘 보이도록 포스팅 할 예정입니다!
이 문제는 컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때,
서로 연결된 컴퓨터 그룹의 개수 즉, 네트워크의 개수를 return 하는 문제이다.
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public static void main(String[] args) {
int n = 3;
//int[][] computers = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
int[][] computers = {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}};
// 1 1 0
// 1 1 0
// 0 0 1
System.out.println(solution(n, computers));
}
public static int solution(int n, int[][] computers) {
int answer = 0;
boolean[] visit = new boolean[n];
for(int i = 0; i < n; i++) {
if (!visit[i]) {
bfs(i, visit, computers);
answer++;
}
}
return answer;
}
public static void bfs(int i, boolean[] visit, int[][] computers) {
Queue<Integer> q = new LinkedList<>();
q.offer(i);
visit[i] = true;
while(!q.isEmpty()) {
int temp = q.poll();
// System.out.print(temp + " ");
for(int j = 1; j < computers.length; j++) {
if(computers[temp][j] == 1 && !visit[j]) {
q.offer(j);
visit[j] = true;
}
}
}
}
}