Notice
Recent Posts
Recent Comments
Link
개발자-H 입니다.
BOJ - 바이러스 본문
https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
- 그래프 문제이다
- 1번에서 출발하여 연결된 모든 노드를 순회만 하면 되기때문에 DFS, BFS 둘다 풀어도 될 것같다.
- 코드는 BFS로 풀었다.
- 1번을 제외한 감염된 컴퓨터를 출력하면 된다.
import java.util.*;
public class Main {
public static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
int N = scanner.nextInt();
int C = scanner.nextInt();
ArrayList<Integer>[] adj = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 1; i <= C; i++) {
int s = scanner.nextInt();
int r = scanner.nextInt();
adj[s].add(r);
adj[r].add(s);
}
boolean[] visited = new boolean[N + 1];
Queue<State> queue = new LinkedList<>();
queue.offer(new State(1, 1));
while (!queue.isEmpty()) {
State node = queue.poll();
if (visited[node.currentNode] == true) continue;
visited[node.currentNode] = true;
for (int i = 0; i < adj[node.currentNode].size(); i++) {
Integer next = adj[node.currentNode].get(i);
if (visited[next] == true) continue;
queue.offer(new State(next, node.depth + 1));
}
}
int numOfVisited = 0;
for (boolean visit : visited) {
if (visit) numOfVisited++;
}
System.out.println(numOfVisited - 1);
}
}
class State {
public int currentNode;
public int depth;
public State(int currentNode, int depth) {
this.currentNode = currentNode;
this.depth = depth;
}
}
'Algorithm > 문제 풀이' 카테고리의 다른 글
BOJ - 숨바꼭질 (1697) (0) | 2021.08.09 |
---|---|
BOJ - 미로 탐색 (2178) (0) | 2021.08.09 |
프로그래머스 - 게임 맵 최단 거리 (0) | 2021.08.08 |
프로그래머스 - 숫자 문자열과 영단어 (0) | 2021.08.08 |
프로그래머스 - 포멧몬 (0) | 2021.08.08 |
Comments