[バージン](Java)2606-ウイルス


質問リンク


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

問題を解く


bfsで解決する.
グラフを2次元配列に変換して解いた.
最初は1番のコンピュータだったので、コンピュータ[1][j]の周りを回転して、1を探して、chk[j]はfalseの値です.その値は次のブラウズのためにキューに配置されます.

コード#コード#

import java.util.*;


public class Main {

    static int[][] computer;
    static boolean[] chk;
    static int n;
    static int m;

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        m = sc.nextInt();
        computer = new int[n + 1][n + 1];

        chk = new boolean[n + 1];

        for (int i = 0; i < m; i++) {
            int y = sc.nextInt();
            int x = sc.nextInt();
            computer[y][x] = 1;
            computer[x][y] = 1;
        }
        //System.out.println(Arrays.deepToString(computer));
        System.out.println(bfs(1));

    }

    public static int bfs(int idx) {
        int answer = 0;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(idx);
        chk[idx] = true;
        while (!queue.isEmpty()) {
            idx = queue.poll();
            for (int i = 1; i <= n; i++) {
                if (computer[idx][i] == 1 && !chk[i]) {
                    queue.add(i);
                    chk[i]= true;
                    computer[i][idx] = 0;
                    answer++;
                }
            }
        }


        return answer;
    }
}