여러 개의 연결 요소가 존재한다.
이 때 1번 점과 연결된 연결 요소에 포함된 점의 개수를 구하는 문제이다.
1번 요소에 대해서만 BFS 혹은 DFS를 수행한다.
이 때 방문한 점의 visit값을 true로 바꿔준다.
BFS, 혹은 DFS가 모두 수행되었다면 visit값이 true인 개수를 세면 된다.
1번 node는 원래부터 바이러스에서 감염되어 있으므로 true인 개수에서 1을 뺀 값이 정답이 될 것이다.
import java.io.*;
import java.util.*;
public class Main {
static int N,M;
static ArrayList<Integer>[] lists;
static boolean[] visit;
static int ans = 0;
static void dfs(int start) {
if(visit[start]) return;
visit[start] = true;
ans++;
// 처음 방문한 점이므로 방문 표기
// 연결 요소에 포함된 Node 개수 하나 증가
for(int s:lists[start]) {
dfs(s);
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
StringBuilder sb = new StringBuilder();
N = sc.nextInt();
M = sc.nextInt();
lists = new ArrayList[N+1];
visit = new boolean[N+1];
for(int i =1;i<N+1;i++) {
lists[i] = new ArrayList<>();
}
for(int i =0;i<M;i++) {
int tmp1 = sc.nextInt();
int tmp2 = sc.nextInt();
lists[tmp1].add(tmp2);
lists[tmp2].add(tmp1);
}
dfs(1); // 1번 점이 start이므로 dfs(1) 수행
System.out.println(ans - 1); // 1번 Node는 정답에서 빼줘야 함
}
static class FastReader // 빠른 입력을 위한 클래스
}