Cod sursa(job #2531578)

Utilizator radustn92Radu Stancu radustn92 Data 26 ianuarie 2020 14:30:55
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

const int NMAX = 100505;
vector<int> graph[NMAX];
int N, M;
bool visited[NMAX];

void read() {
	scanf("%d%d", &N, &M);
	int x, y;
	for (int edgeIdx = 0; edgeIdx < M; edgeIdx++) {
		scanf("%d%d", &x, &y);
		graph[x].push_back(y);
		graph[y].push_back(x);
	}
}

void dfs(int node) {
	visited[node] = true;
	for (auto x : graph[node]) {
		if (!visited[x]) {
			dfs(x);
		}
	}
}

void solve() {
	int countComponents = 0;
	for (int node = 1; node <= N; node++) {
		if (!visited[node]) {
			countComponents++;
			dfs(node);
		}
	}
	printf("%d\n", countComponents);
}

int main() {
	freopen("dfs.in", "r", stdin);
	froepen("dfs.out", "w", stdout);

	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	read();
	solve();
	return 0;
}