문제 설명

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.

컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.

제한사항

입출력 예

n computers return
3 [[1, 1, 0], [1, 1, 0], [0, 0, 1]] 2
3 [[1, 1, 0], [1, 1, 1], [0, 1, 1]] 1

입출력 예 설명

예제 #1

아래와 같이 2개의 네트워크가 있습니다.

cc1e7816-b6d7-4649-98e0-e95ea2007fd7.png

예제 #2

아래와 같이 1개의 네트워크가 있습니다.

edb61632-59f4-4799-9154-de9ca98c9e55.png

package com.example.algorithm.dfs;

import java.util.ArrayList;

public class Network {

    private static ArrayList<Integer>[] computerArray;
    private static boolean[] visited;

    public static void main(String[] args) {
        int[][] array = new int[3][3];
        array[0][0] = 1;
        array[0][1] = 1;
        array[0][2] = 0;
        array[1][0] = 1;
        array[1][1] = 1;
        array[1][2] = 0;
        array[2][0] = 0;
        array[2][1] = 0;
        array[2][2] = 1;

        System.out.println(solution(3, array));
    }

    public static int solution(int n, int[][] computers) {
        computerArray = new ArrayList[n];
        visited = new boolean[n];

        for (int i = 0; i < computers.length; i++) {
            computerArray[i] = new ArrayList<>();
            visited[i] = false;
        }

        for (int i = 0; i < computers.length; i++) {
            for (int j = 0; j < computers.length; j++) {
                if (i == j) continue;
                if (computers[i][j] == 1) {
                    computerArray[i].add(j);
                    computerArray[j].add(i);
                }
            }
        }

        int networksCount = 0;
        for (int i = 0; i < computers.length; i++) {
            if (!visited[i]) {
                dfs(i);
                networksCount++;
            }
        }

        return networksCount;
    }

    private static void dfs(int index) {
        if (visited[index]) return;
        visited[index] = true;

        for (int i: computerArray[index]) {
            if (!visited[i]) {
                dfs(i);
            }
        }
    }
}