카테고리 없음

[Java]프로그래머스-네트워크(DFS/BFS) 문제 풀이 정답 답안

dev-seongsu 2022. 3. 1. 13:35
class Solution {
    public int solution(int n, int[][] computers) {
        int answer = 0;
        boolean[] chk = new boolean[n]; //방문여부저장
    
        for(int i = 0 ; i < computers.length ; i++) {
    
            //해당 컴퓨터가 방문된 적이 없으면
            if(!chk[i]) { 
                //해당 컴퓨터를 시작으로 방문 실행.
                dfs(computers, chk, i);
                //네트워크 하나가 탐색되었음으로 카운트+1
                answer++;
            }
        }
        return answer;
    }
    
    //컴퓨터 연결정보 행렬, 컴퓨터 방문여부, 시작 컴퓨터 
    void dfs(int[][] computers, boolean[] chk ,int start) {
        //시작 컴퓨터 방문
        chk[start] = true;
        for(int i = 0; i < computers[start].length ; i++) {
            //시작 컴퓨터와 연결되어 있는 컴퓨터들을 새 시작점으로 방문 명령
            if(computers[start][i] == 1 && chk[i] == false ) dfs(computers, chk, i);
        }
    }
}