Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

전공공부

[BOJ 2606] 바이러스 본문

Study/Problem Solving

[BOJ 2606] 바이러스

monitor 2023. 8. 12. 13:56

 

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

// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tk = new StringTokenizer(in.readLine(), " ");
        int n = Integer.parseInt(tk.nextToken());
        List<Integer>[] list = new ArrayList[n+1];
        for(int i = 1; i < n+1; i++){
            list[i] = new ArrayList<>();
        }

        tk = new StringTokenizer(in.readLine(), " ");
        int v = Integer.parseInt(tk.nextToken());

        for(int i = 0; i < v; i++){
            tk = new StringTokenizer(in.readLine(), " ");
            int idx = Integer.parseInt(tk.nextToken());
            int go = Integer.parseInt(tk.nextToken());
            list[idx].add(go);
            list[go].add(idx);
        }

        int ans = BFS(list,n);
        System.out.println(ans);
    }

    private static int BFS(List<Integer>[] list,int size) {

        Queue<Integer> q = new LinkedList<Integer>();
        q.add(1);
        int ans = 0;
        boolean[] visited = new boolean[size+1];
        visited[1] = true;
        while(!q.isEmpty()){
            int n = q.poll();
            for (int i = 0; i < list[n].size(); i++) {
                if(!visited[list[n].get(i)]) {
                    visited[list[n].get(i)] = true;
                    ans++;
                    q.add(list[n].get(i));
                }
            }
        }
        return ans;
    }
}

설명이 크게 필요 없는 듯하다. BFS를 사용하였고 적절히 방문여부를 체크하였다.

 

 

 

2606번: 바이러스

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

www.acmicpc.net

 

'Study > Problem Solving' 카테고리의 다른 글

[BOJ 7568] 덩치  (0) 2023.08.20
[BOJ 11286] 절대값 힙  (0) 2023.08.13
[BOJ 8979] 올림픽  (0) 2023.07.30
[BOJ 10431] 줄 세우기  (0) 2023.07.30
[BOJ 9655] 돌 게임  (0) 2023.07.26