[Algorithm - Programmers] 네트워크

nunu·2023년 10월 5일
0

Algorithm

목록 보기
85/142

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

제출 코드

import java.util.*;
class Solution {
    public int solution(int n, int[][] computers) {
       int[] visited = new int[n];
        Arrays.fill(visited, -1);
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            if (visited[i] == -1) {
                Queue<Integer> queue = new LinkedList<>();
                visited[i] = cnt;
                queue.offer(i);
                while (!queue.isEmpty()) {
                    int now = queue.poll();
                    for (int j = 0; j < n; j++) {
                        if (visited[j] == -1 && computers[now][j] == 1) {
                            queue.offer(j);
                            visited[j] = visited[now];
                        }
                    }
                }
                cnt++;
            }
        }
        return cnt;
    }
}
profile
Hello, I'm nunu

0개의 댓글