자기개발👨‍💻/코딩 알고리즘

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

천숭이 2022. 5. 14. 20:46

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

 

2606번: 바이러스

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

www.acmicpc.net

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

vector <int> a[101];
int com, net;
bool check[101];
int cnt=0;

void dfs(int node){
	check[node] = true;
	cnt++;
	for (int i=0;i<a[node].size();i++){
		int next = a[node][i];
		if (check[next]!=true)
			dfs(next);
	}
}

int main(){
	cin >> com >> net;
	int x, y;
	for (int i=0;i<net;i++){
		cin >> x >> y ;
		a[x].push_back(y);
		a[y].push_back(x);
	}
	for (int i=1;i<x;i++){
		sort(a[i].begin(), a[i].end());
	}
	
	dfs(1);
	
	cout << cnt-1;
}

 

- dfs로 해결

- dfs로 풀기 위해서는 배열 내부를 정렬해야 하고, 방문체크를 해야한다