Cod sursa(job #2531579)

Utilizator radustn92Radu Stancu radustn92 Data 26 ianuarie 2020 14:31:45
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 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() {
	cin >> N >> M;
	int x, y;
	for (int edgeIdx = 0; edgeIdx < M; edgeIdx++) {
		cin >> 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);
		}
	}

	cout << countComponents << "\n";
}

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

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

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