728x90
반응형
문제
제출한 답안
package BOJ;
import java.util.Scanner;
public class BOJ_2606 {
private static int[][] graph;
private static boolean[] isVisited;
private static int M;
private static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
M = sc.nextInt();
int N = sc.nextInt();
graph = new int[M+1][M+1];
isVisited = new boolean[M+1];
for (int i = 0; i < N; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
graph[x][y] = graph[y][x] = 1; // 간선(Edge)
}
dfs(1);
System.out.println(count-1);
sc.close();
}
private static void dfs(int vertex){
isVisited[vertex] = true;
count++;
for (int i = 1; i <= M; i++) {
if (graph[vertex][i] == 1 && !isVisited[i]){
isVisited[i] = true;
dfs(i);
}
}
}
}
728x90
반응형
'Algorithm' 카테고리의 다른 글
[BOJ 1012] 유기농 배추 ( with Java ) (0) | 2023.04.16 |
---|---|
[BOJ 2667] 단지번호붙이기 ( with Java ) (0) | 2023.04.16 |
[BOJ 1260] DFS와 BFS ( with Java ) (0) | 2023.04.16 |
LCA(Lowest Common Ancestor) (1) | 2023.04.15 |
DFS & BFS (0) | 2023.04.14 |