void dijkstra(ALGraph G,int s,int d[],int pi[],int Q[]) { //Q[]是最小优先队列,Q[1..n]中存放的是图顶点标号,Q[0]中存放堆的大小 //优先队列中有key的概念,这里key可以从d[]中取得。比如说,Q[2]的大小(key)为 d[ Q[2] ] initSingleSource(G,s,d,pi); //1、初始化结点工作 //2、初始化队列 Q[0] = G.vexnum; int i=1; for(;i<=Q[0];i++) { Q[i] = i-1; } Q[1] = s; Q[s+1] = 0; int u; int v; while(Q[0]!=0) { buildMinHeap(Q,d); //3.1、建立最小堆 u = extractMin(Q,d); //3.2、从最小队列中,抽取最小结点 ArcNode* arcNodePt = G.vertices[u].firstarc; while(arcNodePt!=NULL) { v = arcNodePt->adjvex; relax(u,v,G,d,pi); //4、松弛操作。 arcNodePt = arcNodePt->nextarc; } } }
void Dijkstra(FILE*out, Graph G, int s, char c[]){ int j, heap[MaxVertices + 1], heapLoc[MaxVertices + 1]; initSingleSource(G, s); for (j = 1; j <= G->numV; j++)heap[j] = heapLoc[j] = j; heap[1] = s; heap[s] = 1; heapLoc[s] = 1; heapLoc[1] = s; int heapSize = G->numV; while (heapSize > 0){ int u = heap[1]; if (G->vertex[u].cost == INFINITY)break; siftDown(G, heap[heapSize], heap, 1, heapSize - 1, heapLoc); GEdgePtr p = G->vertex[u].firstEdge; while (p != NULL){ if (G->vertex[u].cost + p->weight < G->vertex[p->child].cost){ G->vertex[p->child].cost = G->vertex[u].cost + p->weight; G->vertex[p->child].parent = u; siftUp(G, heap, heapLoc[p->child], heapLoc); } p = p->nextEdge; } --heapSize; } printCostPath(out, G, c); }