Cod sursa(job #2399488)

Utilizator mihai.constantinConstantin Mihai mihai.constantin Data 7 aprilie 2019 16:29:38
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;

#define dmax 100005

vector<int> graph[dmax];

bool visited[dmax];
int N, M;

int componente;

FILE *in, *out;

void dfs(int x) {

	int i, y;

	visited[x] = true;

	// parcurg vecinii y ai lui x

	for(i = 0; i < graph[x].size(); i++) {
		y = graph[x][i];

		if(!visited[y]) {
			dfs(y);
		}
	}
}

int main() {

	in = fopen("dfs.in", "r");
	out = fopen("dfs.out", "w");

	int i, x, y;

	fscanf(in, "%d %d", &N, &M);

	for(i = 1; i <= M; i++) {
		fscanf(in, "%d %d", &x, &y);
		graph[x].push_back(y);
		graph[y].push_back(x);
	}

	for(i = 1; i <= N; i++) {
		if(!visited[i]){
			dfs(i);
			componente++;
		}
	}

	fprintf(out, "%d\n", componente);

	return 0;
}