Cod sursa(job #2460495)

Utilizator mionelIon. M mionel Data 23 septembrie 2019 19:50:14
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.61 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int n, m;
vector<int> a[100001];
bool viz[100001];

void dfs(int l) {
	viz[l] = true;
    int v, j;
	for(j=0;j<a[l].size();j++){
        v=a[l][j];
		if(!viz[v]) {
			viz[v] = true;
			dfs(v);
		}
	}
}

int main() {
	ifstream in("dfs.in");
	ofstream out("dfs.out");

	in >> n >> m;

	for(int i = 0; i < m; i++) {
		int x, y;
		in >> x >> y;

		a[x].push_back(y);
		a[y].push_back(x);
	}

	int c = 0;
	for(int i = 1; i <= n; i++) {
		if(!viz[i]) {
			dfs(i);
			c++;
		}
	}

	cout << c;
	out << c;

	in.close();
	out.close();
	return 0;
}