코딩테스트

[프로그래머스/Java] 네트워크 (DFS)

데메즈 2026. 7. 10. 20:41
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

import java.util.Stack;

class Solution {
    boolean[] visited;
    Stack<Integer> stack = new Stack<>();
    public int solution(int n, int[][] computers) {
        int answer = 0;
        visited = new boolean[n];
        
        for(int i=0; i<n; i++){
            if(!visited[i]){
                answer += 1;
                stack.push(i);
                dfs(n, computers);
            }
        }
        
        
        return answer;
    }
    
    private void dfs(int n, int[][] computers){
        if(stack.isEmpty()){
            return;
        }
        int current = stack.pop();
        visited[current] = true;
        
        for(int i=0; i<n; i++){
            if(computers[current][i]==1 && !visited[i]){
                stack.push(i);
            }
        }
        dfs(n, computers);
    }
}
반응형