[백준] P2606

동민·2021년 3월 11일
import java.util.Scanner;

public class P2606 {
	private static int[][] matrix;
	private static boolean[] visit;
	private static int v, e;
	private static int answer;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		v = sc.nextInt();
		e = sc.nextInt();
		matrix = new int[v + 1][v + 1];
		visit = new boolean[v + 1];
		for (int i = 1; i <= e; i++) {
			int e1 = sc.nextInt(), e2 = sc.nextInt();
			matrix[e1][e2] = matrix[e2][e1] = 1;
		}
		dfs(1);
		System.out.println(answer);
		sc.close();

	}

	private static void dfs(int s) {
		visit[s] = true;
		for (int i = 1; i < v + 1; i++) {
			if (matrix[s][i] == 1 && !visit[i]) {
				answer++;
				dfs(i);
			}
		}
	}
}
profile
BE Developer

0개의 댓글