728x90
1번 컴퓨터와 연결되어 있는 컴퓨터의 개수를 찾는 문제입니다.
1번 컴퓨터에서 DFS를 통해 연결되어 있는 컴퓨터를 탐색했습니다.
같은 컴퓨터를 탐색할 경우를 제외하기 위해 visit 배열에
이미 방문하였으면 체크를 해두었습니다.
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
vector<int> v[110];
int visit[110];
int c = 0;
void DFS(int x)
{
visit[x] = 1;
++c;
for (int i = 0; i < v[x].size(); ++i) {
if (!visit[v[x][i]]) {
DFS(v[x][i]);
}
}
}
int main(int argc, char *argv[])
{
int n, m;
int a, b;
cin >> n >> m;
memset(visit, 0, sizeof(visit));
for (int i = 0; i < m; ++i) {
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
for (int i = 0; i < v[1].size(); ++i) {
if (!visit[v[1][i]]) {
visit[1] = 1;
DFS(v[1][i]);
}
}
cout << c << endl;
return 0;
}
'알고리즘' 카테고리의 다른 글
[C++] 백준 7576번 토마토 (0) | 2019.09.11 |
---|---|
[C++] 백준 2178번 미로 탐색 (0) | 2019.09.10 |
[C++] 백준 3425번 고스택 (0) | 2019.09.10 |
[C++] 백준 1655번 가운데를 말해요 (0) | 2019.09.10 |
[C++] 백준 11286번 절댓값 힙 (0) | 2019.09.10 |