알고리즘/C++ 풀이 기록

백준 - 2606 바이러스

swanim 2021. 10. 15. 19:54

 

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

 

2606번: 바이러스

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

www.acmicpc.net

 

1. 문제 풀이 아이디어

bfs를 이용해 풀었다. 

 

2. 풀이 코드(C++)

 

#include <iostream>
#include <stdio.h>
#include <vector>
#include <queue>
#define max 101
using namespace std;
bool visited[max];
vector <int> graph[max];

void bfs(int started) {
	int cnt = 0;//웜 바이러스에 걸린 컴퓨터의 수 저장
	queue<int> q;
	q.push(started);
	visited[started] = true;

	while (!q.empty()) {
		int x = q.front();
		q.pop();
		for (int i = 0; i < graph[x].size(); i++) {
			int y = graph[x][i];
			if (!visited[y]) {
				q.push(y);
				visited[y] = true;
				cnt++;
			}
		}
	}
	printf("%d", cnt);
}

int main(void) {
	int com = 0;
	int connected = 0;
	scanf("%d %d", &com, &connected);

	for (int i = 0; i < connected; i++) {
		int a, b;
		scanf("%d %d", &a, &b);
		graph[a].push_back(b);
		graph[b].push_back(a);
	}
	bfs(1);
}

 

3. 배운점

컴퓨터는 100대 이하라고 했으니 max를 101로 해야한다.

 

 

'알고리즘 > C++ 풀이 기록' 카테고리의 다른 글

백준 - 12833 XORXORXOR  (0) 2021.12.22
백준 - 1260 DFS와 BFS  (0) 2021.10.17
백준 - 1755 숫자놀이  (0) 2021.10.14
백준 - 1302 베스트셀러  (0) 2021.09.12
백준 - 1181 단어 정렬  (0) 2021.09.11