Cod sursa(job #830562)

Utilizator un_nenorocitChelcioiu Daniel un_nenorocit Data 7 decembrie 2012 02:44:13
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
# include <stdio.h>
# include <vector>
# define N 1000002

using namespace std;
typedef struct Node {
	int id;
	vector <int> neighbours;
	int dist;
};
Node graph[N];
int source, n, m, k = 1;
void readGraph () {
	FILE *f;
	int x, y;
	int ok = 0;
	f = fopen("bfs.in", "r");
	if (!f){ 
		return;
	}
	fscanf(f, "%i %i %i", &n, &m, &source);
	for (int i = 0; i < m; i++) {
		fscanf (f, "%i %i",&x, &y);
		Node node1 ;
		node1.id = x;
		if (node1.id == y)
			continue;
		ok = 0;
		for (int j = 0; j <	k; j++){ 
			if (graph[j].id == node1.id){
				ok = 1;
				graph[j].neighbours.push_back(y);
				break;
			}
		}
		if (ok == 0){
			graph[node1.id] = node1;
			graph[node1.id].neighbours.push_back(y);
			graph[node1.id].dist = 0;
			k++;
		}
	}
	fclose(f);
}

void printGraph () {
	for (int i = 1; i < k; i++){
		printf("%i: ", graph[i].id);
		for (int j = 0; j < graph[i].neighbours.size(); j++){
            printf("%i ", graph[i].neighbours.at(j));    
        }
		printf("\n");
    }
}

bool contains (int n, vector<int> v){
	for (int i = 0; i < v.size(); i++){
		if (n == v.at(i))
			return true;
	}
	return false;
}

int bfs (int start, int stop) {
vector <int> queue;
vector <int> visited;
queue.push_back(start);
visited.push_back(start);
while (queue.size() > 0) {		
	int n = queue.at(0);
	queue.erase(queue.begin());
	if (n == stop){
		return graph[n].dist;
		}
	for (int i = 0; i < graph[n].neighbours.size(); i++){
		if (contains(graph[n].neighbours.at(i), visited) == false){
			queue.push_back(graph[n].neighbours.at(i));
			visited.push_back(graph[n].neighbours.at(i));
			graph[graph[n].neighbours.at(i)].dist = graph[n].dist + 1;
		}
	}
}
	return -1;
}

int main () {
	readGraph();
	//printGraph();
	FILE *g = fopen ("bfs.out","w");
	for (int i = 1; i < k; i++){
		int dist = bfs(source, i);
		fprintf(g,"%i ", dist);
	}
	fclose(g);
	return 1;
}