[프로그래머스] 네트워크 (java)

HaYeong Jang·2021년 3월 28일
0
post-thumbnail

🔗 문제링크

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

👩🏻‍💻 코드

import java.util.*;

class Solution {
    static boolean[] visited;

    public int solution(int n, int[][] computers) {
        int answer = 0;
        visited = new boolean[computers.length];

        for (int i = 0; i < computers.length; i++) {
            if (!visited[i]) {
                answer++;
                BFS(i, computers);
            }
        }
        return answer;
    }
    
    public static void BFS(int i, int[][] arr) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(i);

        while (!queue.isEmpty()) {
            int cur = queue.poll();
            visited[cur] = true;

            for (int j = 0; j < arr.length; j++) {
                if (!visited[j] && arr[cur][j] == 1) {
                    queue.add(j);
                }
            }
        }
    }
}

📝 정리

BFS를 이용하여 방문하지 않은 노드들을 큐에 추가하고 visited를 변경해 주는 과정을 반복하였다.
그리고 visited가 false인 곳들을 차례대로 세면서 answer를 증가시켜주었다.

profile
기억하기 위해 기록하는 개발로그👣

0개의 댓글