본문 바로가기
알고리즘/완전 탐색

백준 11724번 : 연결 요소의 개수

by Jason95 2021. 1. 3.

문제 링크 : www.acmicpc.net/problem/11724

내 풀이(2021.1.3.) : 

#include <iostream>
#include <queue>

using namespace std;

int visit[1001] = { 0, };
int edge[1001][1001] = { 0, };
int N, M;
int cnt = 0;

void BFS(int root) {
	if (visit[root] == 1) return;
	visit[root] = 1;
	
	cnt++;
	
	queue<int> q;
	q.push(root);

	while (!q.empty()) {
		int n = q.front(); q.pop();
		for (int i = 1; i <= N; i++) {
			if (visit[i] == 0 && edge[n][i] == 1) {
				visit[i] = 1;
				q.push(i);
			}
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> N >> M;

	for (int i = 0; i < M; i++) {
		int u, v; cin >> u >> v;
		edge[u][v] = 1;
		edge[v][u] = 1;
	}

	for (int i = 1; i <= N; i++) {
		BFS(i);
	}
	cout << cnt;

	return 0;
}

while문에 !를 넣는 것을 깜빡했다.

'알고리즘 > 완전 탐색' 카테고리의 다른 글

백준 15654번 : N과 M (5)  (0) 2021.01.05
백트래킹 개념  (0) 2021.01.05
백준 1012번 : 유기농 배추  (0) 2021.01.02
BFS 개념  (0) 2020.12.21
백준 1074번 : Z  (0) 2020.12.17