typedef struct ArcNode {
char adjvex;
ArcNode* nextArc;
int weight;
}ArcNode,*pArcNode;
typedef struct VNode {
char date;
pArcNode firstArc;
}VNode,*pVNode;
typedef struct {
pVNode vert;
int vexnum, arcnum;
}ALGraph;
void Dijkstra(ALGraph G, int v0) {
bool* S = new bool[G.vexnum]; //标记是否找到最短路径
int* Path = new int[G.vexnum]; //储存该路径到终点的前驱节点
int* D = new int[G.vexnum]; //储存距离
for (int v = 0; v < G.vexnum; v++) {
S[v] = false;
D[v] = Infinite;
}
pArcNode p = G.vert[v0].firstArc;
while (p) {
D[locateVex(G, p->adjvex)] = p->weight;
p = p->nextArc;
}
for(int v=0; v < G.vexnum; v++){
if (D[v] < Infinite)Path[v] = v0;
else Path[v] = -1;
}
S[v0] = true;
D[v0] = 0; //初始化完成
for (int i = 1; i < G.vexnum; i++) { //分别算出到每个节点的最短路径
int min = Infinite,v=-1;
for (int w = 0; w < G.vexnum; w++) { //选择该与该点相邻的最短顶点,该点为v
if (!S[w] && D[w] < min) {
v = w; min = D[w];
}
}
if (v != -1) { //当该点为孤立点,避免出错
S[v] = true; //将v加入已选顶点集合
for (int w = 0; w < G.vexnum; w++) { //如果通过v到该点的距离小于原始距离(其他路径的距离),更新前驱节点和距离
int V_to_W = VtoW_distance(G, v, w);
if (!S[w] && (D[w] > D[v] + V_to_W)) {
D[w] = D[v] + V_to_W;
Path[w] = v;
}
}
}
}
for (int i = 0; i < G.vexnum; i++) { //打印最短距离
cout << G.vert[v0].date << "->" << G.vert[i].date << ':' << D[i] << endl;
}
for (int i = 1; i < G.vexnum; i++) { //打印最短路径
if (D[i] == Infinite || v0 == i)continue;
cout << G.vert[v0].date << "到" << G.vert[i].date << "的路径为:";
printPath(G, Path, v0, i);
cout << endl;
}
}
int VtoW_distance(ALGraph G,int v,int w) { //V点到W点的距离
char u = G.vert[w].date;
pArcNode p = G.vert[v].firstArc;
while (p) {
if (p->adjvex == u) {
return p->weight;
}
p = p->nextArc;
}
return Infinite;
}
void printPath(ALGraph G,int* Path, int v0, int v) { //利用递归打印最短路径
if (v0 == v) {
return;
}
printPath(G, Path, v0, Path[v]);
cout << G.vert[Path[v]].date << "->";
return;
}