알고리즘
[백준] 바이러스(9251)
16 views
문제 설명
백준 바이러스 문제 풀이(https://www.acmicpc.net/problem/2606)

문제 개요
해당 문제는 연결된 컴퓨터는 바이러스가 전파되며, 1번 컴퓨터와 연결된 컴퓨터의 개수를 세면 되는 문제이다.
연결 관계, 즉 직접 연결이 되지 않아도 연결 관계에 있는 전체 컴퓨터의 수를 세면 된다.
해당 문제는 DFS, BFS 어떤 것을 써도 문제가 없다.
코드 구현
text
// 백준에서는 첫번째 조건으로 input 받게 설정
// 내 맥북, desktop 에선 두번째걸로 선택됨
const input =
process.platform === "linux"
? require("fs").readFileSync("/dev/stdin").toString().split("\n")
: require("fs").readFileSync("./input.txt").toString().split("\n");
const computer = parseInt(input[0]);
const nodeCount = parseInt(input[1]);
const graph = [...Array(computer + 1)].map((el) => []);
for (let i = 2; i < 2 + nodeCount; i++) {
const [from, to] = input[i].split(" ").map((num) => parseInt(num));
graph[from].push(to);
graph[to].push(from);
}
const visited = [];
const bfs = () => {
const willVisit = [1];
let answer = 0;
while (willVisit.length > 0) {
const data = willVisit.shift();
if (!visited[data]) {
visited[data] = true;
willVisit.push(...graph[data]);
answer++;
}
}
console.log(answer - 1);
};
bfs();
코드 해설
이 문제는 단순히 BFS/DFS 알고리즘을 알면 풀 수 있는 문제이다. 그래프 간 연결 관계가 있는 모든 컴퓨터 수를 세면 된다.
내 로직에서는 1번 컴퓨터까지 포함되어 수가 세어졌기 때문에 마지막에 -1 처리를 해 주었다.
요약 및 참고사항
- 그래프 간 연결관계, 가중치나 방향이 따로 없다면 → BFS / DFS
