Dijkstra算法(c++实现)

void Dijkstra(int s, T d[], int p[]) { //寻找从顶点s出发的最短路径,在d中存储的是s->i的最短距离 //p中存储的是i的父节点 if (s < 1 || s > n) throw OutOfBounds(); //路径可到达的顶点列表,这里可以用最小堆 Chain L; ChainIterator I; //初始化d, p, and L for (int i = 1; i <= n; i++) { d[i] = a[s][i]; if (d[i] == NoEdge) { p[i] = 0; } else { p[i] = s; L.Insert(0,i); } } //更新d, p while (!L.IsEmpty()) { //寻找最小d的点v int *v = I.Initialize(L); int *w = I.Next(); while (w) { if (d[*w] < d[*v]) v = w; w = I.Next(); } int i = *v; L.Delete(*v); for (int j = 1; j <= n; j++) { if (a[i][j] != NoEdge && (!p[j] || d[j] > d[i] + a[i][j])) { // 刷新更小的d[j] d[j] = d[i] + a[i][j]; // 如果j没有父节点,则添加到L if (!p[j]) L.Insert(0,j); // 更新父节点 p[j] = i; } } } }

你可能感兴趣的:(C&C++)