본문 바로가기

백준/C++

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

728x90

 

오늘도 dfs/bfs 문제~~

 

문제 2606번

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

 

2606번: 바이러스

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

www.acmicpc.net

 

이 문제는 dfs나 bfs로 풀면 되는 문제인데, 나는 그냥 bfs로 접근해 count를 1씩 증가시켜가며 문제를 해결하였다.

어제 공부해놔서 그런지 쉽게 풀렸다.

 

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

bool visited[1001];
vector<int> node[1001];

void bfs(int start) {
	int count = 0;
	queue<int> q;

	q.push(start);
	visited[start] = true;
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		for (int i = 0; i < node[x].size(); i++) {
			int y = node[x][i];
			if (!visited[y]) {
				q.push(y);
				visited[y] = true;
				count++;
			}
		}
	}
	cout << count << '\n';
}


int main() {
	int n, m, k, w;
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		cin >> k >> w;
		node[k].push_back(w);
		node[w].push_back(k);
	}
	for (int i = 1; i <= n; i++) {
		sort(node[i].begin(), node[i].end());
	}
	bfs(1);
}

 

 

 

 

728x90

'백준 > C++' 카테고리의 다른 글

[C++] 백준 1697번 - 숨바꼭질  (2) 2024.03.07
[C++] 백준 2178번 - 미로 탐색  (0) 2024.03.07
[C++] 백준 1260번 - DFS와 BFS  (2) 2024.03.04
[C++] 백준 1300번 - K번째 수  (0) 2024.03.04
[C++] 백준 1337번 - 올바른 배열  (0) 2024.03.01