Algorithm/Programmers

[43162] 네트워크

idan 2021. 10. 26. 21:19

문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

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

programmers.co.kr

 

문제 해결 방법

dfs로 구현했다.

 

 

class Solution {
    public int solution(int n, int[][] computers) {
        
        boolean[] chk = new boolean[n];
        int answer = 0;
        
        for(int i = 0; i < n; i++) {
            if(!chk[i]) {
                dfs(computers, chk, i);
                answer++;
            }
        }
        return answer;
    }
    
    public void dfs(int[][] computers, boolean[] chk, int idx) {
        
        for(int i = 0; i < computers.length; i++) {
            if(!chk[i] && computers[idx][i] == 1) {
                chk[i] = true;
                dfs(computers, chk, i);
            }
        }
    }
}