본문 바로가기

코딩테스트(백준)

[백준] 2606 : 바이러스 -JAVA(자바) - 사좋배 공유

 


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
	static int[][] arr;
	static boolean []visit;
	static Queue q = new LinkedList();
	static int size;
	public static void main(String[] args) {
		arr= new int[101][101];
		Scanner sc = new Scanner(System.in);
		size = sc.nextInt();
		int number = sc.nextInt();
		visit =new boolean[size+1];
		for(int i=0;i<number;i++) {
			int x= sc.nextInt();
			int y= sc.nextInt();
			arr[x][y]=1;
			arr[y][x]=1;
			if(x==1||y==1) {
				q.add(new pos(x,y));
			}
		}
		visit[1]=true;
		BFS();
		
		int result=0;
		for(int i=2;i<visit.length;i++) {
			if(visit[i]==true) {
				result++;
			}
		}
		System.out.println(result);

	}
	public static void BFS() {
		while(!q.isEmpty()) {
			pos temp = q.poll();
			int x= temp.x;
			int y= temp.y;
			visit[x]=true;
			visit[y]=true;
			for(int i=0;i<=size;i++) {
				if(arr[y][i]==1) {
					arr[y][i]=0;
					q.add(new pos(y,i));
				}
			}
		}
	}

}
class pos{
	int x;
	int y;
	public pos(int x, int y) {
		this.x = x;
		this.y = y;
	}
}