[백준] 11724 연결 요소의 개수 / BFS, DFS (C++)

sobokii·2023년 10월 25일
0

문제풀이

목록 보기
28/52

문제
방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

입력
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.

출력
첫째 줄에 연결 요소의 개수를 출력한다.

BFS를 외부함수로 빼서 정리하는 습관을 들이자

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

vector<int> map[1001];
vector<bool> ch(1001, false);

void BFS(int n)
{
	queue<int> q;
	q.push(n);
	ch[n] = true;
	while (!q.empty())
	{
		int tmp = q.front();
		q.pop();

		for (int i = 0; i < map[tmp].size(); i++)
		{
			if (ch[map[tmp][i]] == false)
			{
				ch[map[tmp][i]] = true;
				q.push(map[tmp][i]);
			}
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	int N, M, cnt = 0;
	cin >> N >> M;

	for (int i = 0; i < M; i++)
	{
		int a, b;
		cin >> a >> b;
		map[a].push_back(b);
		map[b].push_back(a);
	}
	
	for (int i = 1; i <= N; i++)
	{
		if (ch[i] == false)
		{
			BFS(i);
			cnt++;
		}
	}
	cout << cnt;

	return 0;
}
profile
직장 구하고 있습니다.

0개의 댓글