연습문제/JAVA
[백준 java] 2606-바이러스
나고없
2022. 8. 13. 21:28
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
각 노드의 관계를 그래프에 저장하고 1번 노드와 이어진 노드의 수를 계산하는 문제
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class B2606 {
static int N,M;
static int count = 0;
static int[][] Graph;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
Graph = new int[N+1][N+1];
visited = new boolean[N+1];
for(int i = 0; i<M; i++){
int x = sc.nextInt();
int y = sc.nextInt();
Graph[x][y] = Graph[y][x] = 1;
}
bfs();
System.out.println(count);
}
public static void bfs(){
Queue<Integer> queue = new LinkedList<>();
visited[1]=true;
queue.add(1);
while(!queue.isEmpty()){
int temp = queue.remove();
for(int i=1; i<N+1; i++){
if(!visited[i] && (Graph[temp][i] == 1)){
visited[i] = true;
queue.add(i);
count ++;
}
}
}
}
}