https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어진다. 이어서 그 수만큼 한 줄에 한 쌍씩 네트워크 상에서 직접 연결되어 있는 컴퓨터의 번호 쌍이 주어진다.
www.acmicpc.net
풀이
- 1번 컴퓨터에 연결된 컴퓨터들을 구하면 되는 연결 요소 문제이다. BFS로 풀어주면 될 것 같다.
- 먼저 컴퓨터들의 연결 정보를 인접리스트로 구현해준다.
- 1번 컴퓨터를 먼저 큐에 넣고 1번 컴퓨터와 연결된 컴퓨터들을 모두 방문 체크한다.
- 방문한 컴퓨터(감염된 컴퓨터) 수를 출력 (1번 컴퓨터 제외).
import java.util.*;
public class Main {
static ArrayList<Integer>[] list;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int connect = sc.nextInt();
list = (ArrayList[]) new ArrayList[n];
for(int i=0; i < n; i++) {
list[i] = new ArrayList();
}
for(int i=0; i < connect; i++) {
int u = sc.nextInt()-1;
int v = sc.nextInt()-1;
list[u].add(v);
list[v].add(u);
}
boolean[] check = new boolean[n];
Queue q = new LinkedList();
q.add(0);
check[0] = true;
while(!q.isEmpty()) {
int u = q.remove();
for(int i=0; i < list[u].size(); i++) {
int v = list[u].get(i);
if(check[v]) continue;
q.add(v);
check[v] = true;
}
}
int ans = -1;
for(int i=0; i < n; i++) {
if(check[i]) ans++;
}
System.out.println(ans);
}
}
'BOJ' 카테고리의 다른 글
| [BOJ] 3055. 탈출 (0) | 2019.05.01 |
|---|---|
| [BOJ] 2583. 영역 구하기 (0) | 2019.05.01 |
| [BOJ] 4963. 섬의 개수 (0) | 2019.05.01 |
| [BOJ] 7569. 토마토 (3차원) (0) | 2019.04.30 |
| [BOJ] 7576. 토마토 (0) | 2019.04.30 |