Cod sursa(job #1458041)

Utilizator tony.hegyesAntonius Cezar Hegyes tony.hegyes Data 6 iulie 2015 11:16:20
Problema Parcurgere DFS - componente conexe Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

///// DESCRIPTION
// THIS PROGRAM EMPLOYS DEPTH-FIRST SEARCH
// ON AN INPUT OF AN UNDIRECTED GRAPH
// WITH N VERTICES AND M EDGES
// TO DETERMINE HOW MANY
// CONNECTED COMPONENTS IT HAS
/////

void dfs(int, vector<int>[], bool[], vector<int>);

int main(int argc, char **argv)
{
	// INPUT
	ifstream indata("dfs.in");
	
	int n, m;
	indata >> n >> m;
	
	vector<int> edges[n + 1];
	for (int i = 0, x, y; i < m; i++) {
		indata >> x >> y;
		// there is a path from x to y
		edges[x].push_back(y);
	}
	
	// DFS
	bool visited[n + 1];
	for (int i = 1; i <= n; i++) {
		visited[i] = false;
	}
	
	int connectedComponents = 0;
	for (int i = 1; i <= n; i++) {
		if (visited[i] == true) {
			continue;
		}
		
		connectedComponents++;
		
		vector<int> stack;
		dfs(i, edges, visited, stack);
	}
	
	// OUTPUT
	ofstream outdata("dfs.out");
	outdata << connectedComponents;
	outdata.close();	
	
	return 0;
}

void dfs(int currentNode, vector<int> edges[], bool visited[], vector<int> stack) {
	for (size_t i = 0; i < edges[currentNode].size(); i++) {
		if (visited[edges[currentNode][i]] == false) {
			stack.push_back(edges[currentNode][i]);
		}
	}
	
	visited[currentNode] = true;
	
	if (stack.size() != 0) {
		int nextNode = stack.back();
		stack.pop_back();
		
		dfs(nextNode, edges, visited, stack);
	}
}