슈콩

[BOJ] 백준 2606 바이러스 본문

Algorithms/Baekjoon

[BOJ] 백준 2606 바이러스

shukong 2025. 9. 29. 19:19

[문제]

https://www.acmicpc.net/problem/2606

 

 

[소스 코드]

import java.io.*;
import java.util.*;


public class Main {
	static int n,result = 0;
	static boolean[][] edge;
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		n = Integer.parseInt(br.readLine());
		edge = new boolean[n+1][n+1];
		int m = Integer.parseInt(br.readLine());
		for(int i=0;i<m;i++) {
			st = new StringTokenizer(br.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			edge[a][b] = true; 
			edge[b][a] = true;
		}
		bfs();
		System.out.println(result);
	}
	private static void bfs() {
		Queue<Integer> q = new LinkedList<>();
		boolean[] visit = new boolean[n+1];
		visit[1] = true;
		q.offer(1);
		
		while(!q.isEmpty()) {
			int curr = q.poll();
			for(int i=2;i<=n;i++) {
				if(!visit[i] && edge[curr][i]) {
					result++;
					visit[i] = true;
					q.offer(i);
				}
			}
		}
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 백준 2644 촌수계산  (0) 2025.09.29
[BOJ] 백준 2667 단지번호붙이기  (0) 2025.09.29
[BOJ] 백준 2178 미로 탐색  (0) 2025.09.29
[BOJ] 백준 1260 DFS와 BFS  (0) 2025.09.29
[BOJ] 백준 23289 온풍기 안녕!  (2) 2025.09.27