알고리즘
[java] 백준 2606 : 바이러스
_DAMI
2023. 4. 30. 20:23
문제
https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
bfs만 하니까 쉽게 풀렸다..
코드
package main;
import java.util.*;
public class Main {
static int N;
static int M;
static int count=0;
static ArrayList<Integer>[] arr;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); //컴퓨터 번호
M = sc.nextInt(); //연결 수
visited = new boolean[N+1];
arr = new ArrayList[N+1];
for(int i=1; i<=N; i++) {
arr[i] = new ArrayList<Integer>();
}
for(int i=1; i<=M; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
arr[x].add(y);
arr[y].add(x);
}
BFS();
System.out.println(count);
}
static void BFS() {
Queue<Integer> q = new LinkedList<>();
q.add(1);
visited[1]=true;
while(!q.isEmpty()) {
int now = q.poll();
for(int x : arr[now]) {
if(visited[x]!=true) {
q.add(x);
visited[x]=true;
count++;
}
}
}
}
}