[BOJ] 2606. 바이러스
15 Apr 2026
Reading time ~1 minute
풀이
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int N, M;
static ArrayList<Integer>[] edge;
static boolean[] check;
static int ans;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
edge = new ArrayList[N+1];
check = new boolean[N+1];
for(int i = 1; i <= N; i++) {
edge[i] = new ArrayList<>();
}
for(int i = 0; i < M; i++) {
int v1 = sc.nextInt();
int v2 = sc.nextInt();
edge[v1].add(v2);
edge[v2].add(v1);
}
bfs(1);
System.out.println(ans);
}
static void bfs(int V) {
Queue<Integer> q = new LinkedList<>();
q.add(V); check[V] = true;
while(!q.isEmpty()) {
int v = q.poll();
for(int i = 0; i < edge[v].size(); i++) {
int nv = edge[v].get(i);
if(!check[nv]) {
q.add(nv);
check[nv] = true;
ans++;
}
}
}
}
}