11724번: 연결 요소의 개수
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주
www.acmicpc.net
#include <cstdio>
#include <vector>
using namespace std;
vector<int> a[1001];
bool check[1001];
void dfs(int node) {
check[node] = true;
for (int i=0; i<a[node].size(); i++) {
int next = a[node][i];
if (check[next] == false) {
dfs(next);
}
}
}
int main() {
int n, m;
scanf("%d %d",&n,&m);
for (int i=0; i<m; i++) {
int u,v;
scanf("%d %d",&u,&v);
a[u].push_back(v);
a[v].push_back(u);
}
int components = 0;
for (int i=1; i<=n; i++) {
if (check[i] == false) {
dfs(i);
components += 1;
}
}
printf("%d\n",components);
return 0;
}
'Problem set' 카테고리의 다른 글
[백준] 2667 단지번호붙이기 (0) | 2021.02.20 |
---|---|
[백준] 1707 이분 그래프 (0) | 2021.02.20 |
[백준] 1260 DFS와 BFS (0) | 2021.02.20 |
[백준] 13023 ABCDE (0) | 2021.02.20 |
[백준] 14391 종이 조각 (0) | 2021.02.20 |