2606 바이러스 - JAVA

또 bfs 문제 이번에는 다른 블로그를 참고하지 않고 나만의 힘으로 풀어보기로 했다. 물론 아예 0부터 짜지는 않고 내가 이전에 했던 bfs 문제를 보면서 했다.. 아예 생짜로 짤 수있을 때까지 해보자,,,,

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

    static boolean[] visited;
    static int[][] arr;
    static int N, M;
    static int count = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        N = Integer.parseInt(br.readLine());
        M = Integer.parseInt(br.readLine());

        visited = new boolean[N + 1];
        arr = new int[N + 1][N + 1];

        for (int i = 0; i < M; i++) {
            StringTokenizer str = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(str.nextToken());
            int b = Integer.parseInt(str.nextToken());
            arr[a][b] = arr[b][a] = 1;
        }

        bfs();
        System.out.println(count);

    }

    public static void bfs() {
        Queue<Integer> q = new LinkedList<>();
        q.add(1);
        visited[1] = true;

        while (!q.isEmpty()) {
            int start = q.poll();
            for (int i = 1; i <= N; i++) {
                if (arr[start][i] == 1 && !visited[i]){
                    q.add(i);
                    visited[i] = true;
                    count++;
                }
            }
        }
    }
}

풀이는 전형적인 bfs 문제의 풀이이다. 그래도 이제 풀이 구조는 이해해서 눈에만 좀 더 익으면 식은죽 먹듯 풀 수 있을 것 같다.