[백준] 2606- 바이러스

zzenee·2022년 10월 5일
0

Algorithm&Coding-test

목록 보기
25/30

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

Problem

Code

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

public class Prob2606 {
      static ArrayList<ArrayList<Integer>> arr;
      static int count;
      static int[] visited;

	public void BFS () {
            Queue<Integer> q = new LinkedList<>();
            q.offer(1);
            while(!q.isEmpty()) {
                  int now = q.poll();
                  for (int next : arr.get(now)) {
                        if (visited[next] == 0) {
                              visited[next] = 1;
                              q.offer(next);
                              count++;
                        }
                  }
            }
	}

  	public static void main(String[] args) throws IOException{
            Prob2606 ex = new Prob2606();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int comp = Integer.parseInt(br.readLine());
            int n = Integer.parseInt(br.readLine());
            arr = new ArrayList<ArrayList<Integer>>();
            for (int j=0; j<=comp; j++) {
                  arr.add(new ArrayList<Integer>());
            }
            for (int i=0; i<n; i++) {
                  StringTokenizer st = new StringTokenizer(br.readLine());
                  int start = Integer.parseInt(st.nextToken());
                  int end = Integer.parseInt(st.nextToken());
                  arr.get(start).add(end);
                  arr.get(end).add(start);
            }
            visited = new int[comp+1];
            visited[1] = 1;
            ex.BFS();
            System.out.print(count);
  	}
}

Result

profile
꾸준히

0개의 댓글