Exemplo n.º 1
0
Set 
*dijkstra(Graph *g, Label v, int Home, int n) {
	// for the school vertex v, find all indices for homes and put all into
	// a set
	Heap *H;
	Edge *Eu;
	Set *S;
	int i, usize;
	Label u;
	float R[n], delta;
	// create a heap to store the distance for every vertices
	// and an array to store dist values
	H = createHeap();
	for (i=0;i<n;i++) {
		if (i==v) {
			insert(H, i, 0);
			R[i]=0;
			continue;
		}
		insert(H, i, INFINITY);
		R[i] = INFINITY;
	}
	// then loop through the heap
	while (H->n) {
		// extract the min in the heap
		u = removeMin(H);
		// if dist of u exceeds 1km, stop the loop
		if (R[u]>1000) {
			break;
		}
		Eu = graph_get_edge_array(g, u, &usize);
		for (i=0;i<usize;i++) {
			if (R[Eu[i].u]>R[u]+ *(float*)(Eu[i].data)) {
				delta = R[u] + *(float*)(Eu[i].data) - R[Eu[i].u];
				changeKey(H, Eu[i].u, delta);
				R[Eu[i].u] = R[u]+ *(float*)(Eu[i].data);
			}
		}
	}
	// now add all home indices with in the range of 1km into the set
	S = set_new();
	for (i=0;i<Home;i++) {
		if (R[i]<=1000) {
			set_add(S, i);
		}
	}
	return S;
}
Exemplo n.º 2
0
void Dijkstra(Graph *g,int source,Universe *Uni,int (cmp)(int,int)) {

    int *dist;

    dist = (int*)malloc(sizeof(int)*(g->number_of_vertices));
    assert(dist);
   
    //set all vertices distance to INF
    for(int i=0;i<g->number_of_vertices;i++) {
        dist[i] = INF;
    }



    Heap *Q = createHeap();
    //insert everything into heap
    for(int i=0;i<g->number_of_vertices;i++) {

        if(i==source) {
            insert_in_heap(Q,i,0,cmp);
        }
        else {
            insert_in_heap(Q,i,INF,cmp);
        }
    }
    // update the distance of source 
    dist[source] = 0;
    
 

    while(!isEmpty(Q)) {


       
        HeapItem min  = removeTop(Q,cmp);

        // min can't be > 1000, if so we can stop
         if(min.key > MAX_KM) {
            break;
        }
        // prune any schools, only houses
        if(min.dataIndex < g->num_houses) {
            insert(Uni, source-g->num_houses, min.dataIndex);
        }       

        int n_edges;
        //get all edges from min.dataIndex
        Edge *edges = graph_get_edge_array(g,min.dataIndex,&n_edges);
       



        for(int i=0;i<n_edges;i++) {

        	//update all the edges distances if there is a minimum 
            if(dist[edges[i].u] > (dist[min.dataIndex] +edges[i].weight)) {
                
                dist[edges[i].u] = dist[min.dataIndex]+edges[i].weight;
                // update the heap
                changeKey(Q,edges[i].u,dist[edges[i].u],cmp);
                                
            }

        }
    
    }

    
}