네트워크


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

문제보기
Alt text

소스코드

import java.util.ArrayDeque;
import java.util.Queue;

class Solution {
    static class Location {
        int x;
        int y;

        public Location(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    private static boolean[][] visited;

    public static int solution(int n, int[][] computers) {
        int network = 0;

        visited = new boolean[n][n];
        Queue<Location> queue = new ArrayDeque<>();

        for (int i = 0; i < n; i++) {
            boolean hasNewNetwork = false;
            for (int j = 0; j < n; j++) {
                if (isNetwork(computers, i, j)) {
                    hasNewNetwork = true;

                    visited[i][j] = true;
                    visited[j][i] = true;

                    if (i != j) {
                        queue.add(new Location(i, j));
                    }
                }
            }

            if (!queue.isEmpty()) {
                bfs(computers, queue);
            }

            if (hasNewNetwork) {
                network++;
            }
        }

        return network;
    }


    private static void bfs(int[][] computers, Queue<Location> queue) {
        while (!queue.isEmpty()) {
            Location location = queue.poll();

            for (int i = 0; i < computers.length; i++) {
                int newX = location.y;
                int newY = i;

                if (isNetwork(computers, newX, newY)) {
                    visited[newX][newY] = true;
                    visited[newY][newX] = true;

                    if (newX != newY) {
                        queue.add(new Location(newX, newY));
                    }
                }
            }
        }
    }

    private static boolean isNetwork(int[][] computers, int x, int y) {
        return computers[x][y] == 1 && !visited[x][y];
    }
}