Algorithm/Baekjoon

[백준 11724] Java - dfs 탐색

say! 2025. 2. 24. 23:10
728x90

import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {

    static int N, M; // 정점, 간선 개수
    static ArrayList<Integer>[] adjList; // 인근 노드
    static boolean[] visited; // 노드 방문여부
    static int cnt; //연결 요소 개수

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        // 정점, 간선 개수 입력받기
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        adjList = new ArrayList[N+1]; // 노드 1번부터 시작
        for(int i=1; i<=N; i++){
            adjList[i] = new ArrayList<>();
        }
        visited = new boolean[N+1];
        // 간선 입력받기
        for(int i=1; i<=M; i++){
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());

            // 방향 없는 그래프
            adjList[u].add(v);
            adjList[v].add(u);
        }

        //bfs 탐색으로 연결 요소 구하기
        for(int i=1; i<=N; i++){
            if(visited[i]){ // 이미 방문한 노드 제외
                continue;
            }
            bfs(i);
            cnt++;
        }
        // 결과 출력
        System.out.println(cnt);
    } //main

    static void bfs(int start){
        for(int n : adjList[start]){
            if(visited[n]){
                continue;
            }
            visited[n] = true;
            bfs(n);
        }
    }
}