Koala - 11기/코딩테스트 준비 스터디

[C++] 백준 2606번: 바이러스

luciduskim 2023. 8. 16. 16:57

https://www.acmicpc.net/problem/2606

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하인 양의 정수이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍

www.acmicpc.net

1. 문제풀이

 네트워크 연결 상태를 확인 후, 1번 컴퓨터가 바이러스에 걸렸을 때 전파될 수 있는 컴퓨터의 수를 구하는 탐색 문제이다. 깊이 우선 탐색 문제 중 하나로, 네트워크 연결 상태를 입력받은 후 인접 리스트의 형태로 그래프 정보를 저장한 후, 1번 컴퓨터를 매개변수로 하여 깊이 우선 탐색을 진행하였다. 다른 컴퓨터를 방문할 때마다 바이러스에 걸린 컴퓨터의 수를 1씩 증가시킨다.

2. C++ 코드

#include <iostream>
#include <queue>
#include <vector>
#include <stdio.h>
#include <string.h>

using namespace std;

int n, m, res;
int visited[101];
vector<int> graph[101];

void bfs(int start)
{
	queue<int> q;
	visited[start] = 1;
	q.push(start);
	while (!q.empty()) {
		int node = q.front();
		q.pop();
		for (int i = 0; i < graph[node].size(); i++) {
			int next = graph[node][i];
			if (!visited[next]) {
				visited[next] = 1;
				q.push(next);
				res++;
			}
		}
	}
}

int main(void)
{
	int com1, com2;
	scanf("%d", &n);
	scanf("%d", &m);
	for (int i = 0; i < m; i++) {
		scanf("%d %d", &com1, &com2);
		graph[com1].push_back(com2);
		graph[com2].push_back(com1);
	}
	bfs(1);
	printf("%d\n", res);

	return 0;
}