알고리즘

백준 2606번 바이러스 (JAVA)

박카스마시며코딩 2024. 1. 10. 13:24

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

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하인 양의 정수이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍

www.acmicpc.net

 

저는 BFS를 통해 문제를 해결하였습니다.

1에서 BFS를 시작하여 연결되어 있는 노드의 개수를 확인하여 문제를 풀었습니다.

 

package BOJ.bfs;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class BOJ_2606 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int edgeCnt = Integer.parseInt(br.readLine());
        List<Integer>[] map = new List[n+1];
        for(int i = 0 ; i <= n ; i++){
            map[i] = new ArrayList<>();
        }
        for(int i = 0 ; i < edgeCnt ; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            map[a].add(b);
            map[b].add(a);
        }
        int result = cal(map,n);
        System.out.println(result);
    }

    private static int cal(List<Integer>[] map, int n) {
        Queue<Integer> q = new LinkedList<>();
        q.offer(1);
        boolean[] visited = new boolean[n+1];
        visited[1] = true;
        int cnt = 0;
        while(!q.isEmpty()){
            int now = q.poll();
            for(int next : map[now]){
                if(!visited[next]){
                    visited[next] = true;
                    q.offer(next);
                    cnt++;
                }
            }
        }
        return cnt;
    }
}