Study/Baekjoon
Baekjoon2606: 바이러스
devyoseph
2022. 1. 10. 09:59
바이러스
1 초 | 128 MB | 82746 | 38783 | 26422 | 45.469% |
문제
신종 바이러스인 웜 바이러스는 네트워크를 통해 전파된다. 한 컴퓨터가 웜 바이러스에 걸리면 그 컴퓨터와 네트워크 상에서 연결되어 있는 모든 컴퓨터는 웜 바이러스에 걸리게 된다.
예를 들어 7대의 컴퓨터가 <그림 1>과 같이 네트워크 상에서 연결되어 있다고 하자. 1번 컴퓨터가 웜 바이러스에 걸리면 웜 바이러스는 2번과 5번 컴퓨터를 거쳐 3번과 6번 컴퓨터까지 전파되어 2, 3, 5, 6 네 대의 컴퓨터는 웜 바이러스에 걸리게 된다. 하지만 4번과 7번 컴퓨터는 1번 컴퓨터와 네트워크상에서 연결되어 있지 않기 때문에 영향을 받지 않는다.

어느 날 1번 컴퓨터가 웜 바이러스에 걸렸다. 컴퓨터의 수와 네트워크 상에서 서로 연결되어 있는 정보가 주어질 때, 1번 컴퓨터를 통해 웜 바이러스에 걸리게 되는 컴퓨터의 수를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어진다. 이어서 그 수만큼 한 줄에 한 쌍씩 네트워크 상에서 직접 연결되어 있는 컴퓨터의 번호 쌍이 주어진다.
출력
1번 컴퓨터가 웜 바이러스에 걸렸을 때, 1번 컴퓨터를 통해 웜 바이러스에 걸리게 되는 컴퓨터의 수를 첫째 줄에 출력한다.

풀이
DFS나 BFS로 풀이할 수 있다.
논리형 배열을 통해 탐색을 했는지 체크하면서 count++을 해주면 총 몇 개가 탐색됐는지 알 수 있을 것이다.
DFS
import java.util.*;
public class Main {
static boolean[] check;
static boolean[][] arr;
static int N;
static int count=0;
public static void dfs(int i) {
check[i]=true;
count++;
for(int j=1;j<=N;j++) {
if(arr[i][j]&&!check[j]) {
dfs(j);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr=new boolean[N+1][N+1];
int input = sc.nextInt();
while(input-->0) {
int x = sc.nextInt();
int y= sc.nextInt();
arr[x][y]=true;
arr[y][x]=true;
}
check=new boolean[N+1];
dfs(1);
System.out.println(count-1);
}}
BFS
import java.util.*;
public class Main {
static boolean[] check;
static boolean[][] arr;
static int N;
static int count=0;
public static void bfs(int n) {
check[n]=true;
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(n);
while(!queue.isEmpty()) {
int now = queue.poll();
for(int i=1;i<=N;i++) {
if(arr[now][i]&&!check[i]) {
count++;
queue.offer(i);
check[i]=true;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr=new boolean[N+1][N+1];
int input = sc.nextInt();
while(input-->0) {
int x = sc.nextInt();
int y= sc.nextInt();
arr[x][y]=true;
arr[y][x]=true;
}
check=new boolean[N+1];
bfs(1);
System.out.println(count);
}}