Cod sursa(job #3156416)

Utilizator adistancu10Stancu Adrian adistancu10 Data 11 octombrie 2023 16:36:50
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.58 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
const int NMAX = 100000;
vector <int> G[NMAX + 1];
int vis[NMAX + 1];
ifstream fin("dfs.in");
ofstream fout("dfs.out");

void DFS(int x) {
	//cout << x << " ";
	vis[x] = 1;
	for (auto next : G[x]) {
		if (!vis[next])
			DFS(next);
	}
}
int main()
{
	int n, m;
	fin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y;
		fin >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
	int cc = 0;
	for (int i = 1; i <= n; i++) {
		if (!vis[i]) {
			cc++;
			DFS(i);
		}
	}
	fout << cc;
}