Cod sursa(job #674525)

Utilizator ukiandreaAndreea Lucau ukiandrea Data 6 februarie 2012 14:36:04
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <stdio.h>
#include <stdlib.h>

#include <queue>

struct node {
	int value;
	int weight;
	struct node *next;
};

struct list {
	node *head;
};

list* create_list()
{
	list *l = (list*)calloc(1, sizeof(list));
	l->head = NULL;
	return l;
}

void insert_list(list* l, int value, int weight)
{
    node *n = (node*)calloc(1, sizeof(node));
	n->value = value;
	n->weight = weight;
    n->next = l->head;

	if (l->head == NULL) 
        l->head = n;
}

void destroy_list(list **l)
{
	while ((*l)->head != NULL) {
		node *p = (*l)->head;
		(*l)->head = (*l)->head->next;
		
		free(p);
	}
}

enum colors {
	WHITE = 0,
	GRAY,
	BLACK
};

struct graph {
	int n;
	list **adj;
	int *colors;
	int *distances;
};

graph* create_graph(int size)
{
	graph *g = (graph*)calloc(1, sizeof(graph));
	g->n = size;
	g->adj = (list**)calloc(size, sizeof(list*));
	g->colors = (int*)calloc(size, sizeof(int));
	g->distances = (int*)calloc(size, sizeof(int));

	return g;
}

void add_graph_edge(graph *g, int v1, int v2, int w)
{
	if (g->adj[v1] == NULL) 
		g->adj[v1] = create_list();

	insert_list(g->adj[v1], v2, w);
}

void clear_graph_value(graph *g)
{
	for (int i = 0; i < g->n; i++) {
		g->colors[i] = WHITE;
		g->distances[i] =  -1;
	}
}

void destroy_graph(graph **g)
{
	for (int i = 0; i < (*g)->n; i++) {
		if ((*g)->adj[i])
			destroy_list(&((*g)->adj[i]));
	}

	free((*g)->adj);
	free((*g)->colors);
	free((*g)->distances);
	free(*g);
}

void bfs(graph *g, int s)
{
	std::queue<int> nodes;

	clear_graph_value(g);

	g->colors[s] = GRAY;
	g->distances[s] = 0;

	nodes.push(s);
	while (nodes.size()) {
		int x = nodes.front();
		node *n = NULL;
		if (g->adj[x])
			n = g->adj[x]->head;

		while (n) {
			if (g->colors[n->value] == WHITE) {
				g->colors[n->value] = GRAY;
				g->distances[n->value] = 1 + g->distances[x];
				nodes.push(n->value);
			}
			n = n->next;
		}
		nodes.pop();
	}
}

int main()
{
	int v, e, s;
	graph * g = NULL;

    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);

	scanf("%d %d %d\n", &v, &e, &s);
	g = create_graph(v);

	for (int i = 0; i < e; i++) {
		int v1, v2;

		scanf("%d %d\n", &v1, &v2);
		add_graph_edge(g, v1 - 1, v2 - 1, 0);
	}
    
    bfs(g, s - 1);

    for (int i = 0; i < g->n; i++) 
        printf("%d ", g->distances[i]);
    printf("\n");

	destroy_graph(&g);

	return 0;
}