본문 바로가기

프로그래머스 - JAVA

코딩테스트 연습 > 깊이/너비 우선 탐색(DFS/BFS) > 네트워크

이전 코드

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

최근 코드

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