[알고리즘/백준] #11724 연결 요소의 개수

JudyLia·2022년 2월 12일
0

알고리즘

목록 보기
38/61
post-thumbnail

난이도: Silver2
문제) 방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

package algorithm_study.day0212;

import java.util.ArrayList;
import java.util.Scanner;

public class BJ_11724 {
	static ArrayList<Integer> graph[];
	static boolean[] check;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int N = sc.nextInt();
		int M = sc.nextInt();
		
		graph = new ArrayList[N+1];
		check = new boolean[N+1];
		int cnt=0;
		
		for(int i=0;i<=N;i++) {
			graph[i]=new ArrayList<Integer>();
		}
		for(int i=0;i<M;i++) {
			int idx = sc.nextInt();
			int element = sc.nextInt();
			
			graph[idx].add(element);
			graph[element].add(idx);
		}
		for(int i=1;i<=N;i++) {
			if(!check[i]) {
				dfs(i);
				cnt++;
			}
		}
		System.out.println(cnt);
	}
	
	static void dfs(int num) {
		if(check[num]) return;
		check[num]=true;
		for(int x: graph[num]) {
			if(!check[x]) dfs(x);
		}
	}
}
profile
안녕:)

0개의 댓글

관련 채용 정보