기록하는 개발자

[백준][JAVA] 11724 : 연결 요소의 개수 본문

Algorithm

[백준][JAVA] 11724 : 연결 요소의 개수

밍맹030 2021. 7. 11. 15:57
728x90

import java.io.*;
import java.util.*;
public class Main{
    static int[][] adjacent= new int[1001][1001];
    static boolean[] checked= new boolean[1001];
    static int n,m;

    public static void main(String[] args) throws IOException {
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        m = s.nextInt();

        for(int i = 0; i < m; i++) {
            int x = s.nextInt();
            int y = s.nextInt();
            adjacent[x][y] = adjacent[y][x] = 1;
        }

        int result=0;
        for(int i = 1; i<=n; i++) {
            if(checked[i]==false){
                dfs(i);
                result++;
            }
        }
        System.out.println(result);
    }

    public static void dfs(int idx) {
        if(checked[idx] == true) return; //확인한 정점을 1로 초기화
        else{
            checked[idx] = true;
            for(int i = 1; i <=n; i++)
                if(adjacent[idx][i] == 1) dfs(i);
        }
    }
}

728x90