[백준 2606/C++] 바이러스

이진중·2022년 5월 29일
0

알고리즘

목록 보기
37/76

바이러스


문제 및 풀이

1번 정점에 연결된 정점들을 dfs나 bfs를 이용하여 탐색하면된다.
탐색을 하면서 카운트를 한개씩 올린다.

실제 코드

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
#define endl "\n"

#define MAX 100+1
int n, k;
vector<int> graph[MAX];
bool visited[MAX];
int ans;

void dfs(int v) {
	ans++;
	visited[v] = true;

	for (auto w : graph[v]) {
		
		if (!visited[w])
		{
			dfs(w);
		}
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	//ifstream cin; cin.open("input.txt");

	cin >> n >> k;
	while (k--)
	{
		int x, y;
		cin >> x >> y;

		graph[x].push_back(y);
		graph[y].push_back(x);
	}

	dfs(1);
	cout << ans-1;
	


}

0개의 댓글