11724번: 연결 요소의 개수 (acmicpc.net)
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
1~1000개를 다 검사할 필요x
n개 정점만 검사하면됨.
for (int i = 1; i <= n; ++i)
{
if (v[i] == 0)
{
dfs(i);
ret++;
}
}
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int n, m,t1,t2,ret, a[1004][1004], v[1004];
int dx[] = {0,1,-1,0};
int dy[] = {1,0,0,-1};
void dfs(int here)
{
v[here] = 1;
//cout << here << " ";
for (int there = 0; there < 1004; ++there)
{
if (a[here][there] == 1 && v[there] == 0)
dfs(there);
}
return;
}
void bfs(int start)
{
queue<int> q;
q.push(start);
int here;
while (q.size())
{
here = q.front(); q.pop();
v[here] = 1;
//cout << here << " ";
for (int there = 0; there < 1004; ++there)
{
if (a[here][there] == 1 && v[there] == 0)
{
q.push(there);
v[there] = 1;
ret++;
}
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(NULL);
cin >> n>>m;
for (int i = 0; i < m; ++i)
{
cin >> t1 >> t2;
a[t1][t2] = 1;
a[t2][t1] = 1;
}
//dfs(v);
//for (int i = 0; i < 1004; ++i) visited[i] = 0;
//cout << "\n";
for (int i = 1; i <= n; ++i)
{
if (v[i] == 0)
{
dfs(i);
ret++;
}
}
cout << ret;
return 0;
}
'Algorithm > boj' 카테고리의 다른 글
백준 2910 빈도정렬 // 커스텀정렬, 인덱스에 의미부여 (0) | 2023.05.03 |
---|---|
백준 7562 // 최단거리는 bfs, 핵심로직공부 (0) | 2023.05.02 |
백준 1260 //dfs-bfs하는법 , 연결정보준경우 (0) | 2023.05.01 |
백준 2667 // int dfs사용법, scanf-cin혼용금지 (0) | 2023.05.01 |
백준 2583 영역구하기 //int dfs , ny>=mn체크 , 좌표를배열로바꾸기 (0) | 2023.04.09 |