본문 바로가기
프로그래머스/코딩테스트 고득점 kit

프로그래머스 깊이/너비 우선 탐색(DFS/BFS) LV3 - 네트워크

by 맴썰 2025. 9. 29.

https://school.programmers.co.kr/learn/courses/30/lessons/43162?language=java

 

프로그래머스

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

programmers.co.kr

정점의 개수와 간선 정보가 주어졌을 때, 연결된 정점 그룹의 개수를 구하는 문제이다.

DFS를 이용해 count했다.

 

class Solution {
    public int solution(int n, int[][] computers) {
        boolean[] visited = new boolean[n];
        int count = 0;
        for(int i = 0; i<n; i++){
            if(visited[i]) continue;
            dfs(i, computers, visited);
            count++;
        }
        return count;
    }
    
    void dfs(int n, int[][] computers, boolean[] visited){
        if(visited[n]) return;
        visited[n] = true;
        for(int i = 0; i< computers[n].length; i++){
            if(i == n) continue;
            if(computers[n][i]==1){
                dfs(i, computers, visited);
            }
        }
    } 
}