[백준] 바이러스

ERror.ASER·2021년 4월 14일
0

백준

목록 보기
48/69
package com.study.classAlgo;

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

public class BOJ2606_바이러스 {
	static class Virus {
		int x;
		int y;
		
		public Virus(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}
	}
	
	static int N,M;
	static int[][] map;
	static boolean[] isSelected;
	static Queue<Virus> queue = new LinkedList<>();
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());//7
		M = Integer.parseInt(br.readLine());//6
		map = new int[N+1][N+1];
		isSelected = new boolean[N+1];
		
		for(int t = 0; t<M; t++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());
			
			map[x][y] = map[y][x] = 1;
			if(map[1][y] == 1) queue.offer(new Virus(1,y));
		}
		isSelected[1] = true;
		bfs();

		System.out.println(result());
		
	}
	
	private static int result() {
		
		int count = 0;
		for (int i = 1; i < N+1; i++) {
			if(isSelected[i]) count++;
		}		
		return count-1;
	}

	private static void bfs() {
		
		while(!queue.isEmpty()) {
			Virus v = queue.poll();
			int to = v.y;
			isSelected[to] = true;
			for(int i=1; i<N+1; i++) {
				if(map[to][i] == 1 && !isSelected[i]) {
					queue.offer(new Virus(to,i));
					isSelected[i] = true;
				}
			}
		}
		
		
	}

}
profile
지우의 블로그

0개의 댓글