图的邻接表实现迪杰斯特拉算法求最短路径

存储结构定义:

typedef struct ArcNode {
	int adjvex;//该弧所指向的顶点的位置
	struct ArcNode *nextarc;//指向下一条弧的指针
	int length;
	int price;
	VertexType departurecity;
	VertexType arrivalcity;
} ArcNode;//弧

typedef struct VNode {
	VertexType CityName;//顶点信息
	ArcNode *firstarc;//指向第一条依附该顶点的弧的指针
}VNode,AdjList[MAX_VERTEX_NUM];//顶点

typedef struct {
	AdjList vertices;
	int vexnum,arcnum;//图的顶点数和弧数
}ALGraph;//图


最短路径算法:

//求得两个城市间最快到达路径,即图中两个顶点的最短路径
//利用迪杰斯特拉算法求图g中从顶点i到j的一条最短路径
void GetFastestPath(ALGraph g,int i,int j) {
	PathType path[MAX_VERTEX_NUM];
	int found,min,v,w,k,pathLength,dist[MAX_VERTEX_NUM],visited[MAX_VERTEX_NUM];
	ArcNode *p;
	PType PathVal;
	for(k=0;kadjvex] = p->length;//dist数组记录邻接边的长度
		InsertPath(path[p->adjvex],i,p->adjvex);//保存路径在path数组的对应位置中
		p = p->nextarc;
	}
	/*
	printf("********debugging info***********\n");
	printf("9:%d\n",dist[9]);
	printf("7:%d\n",dist[7]);
	printf("1:%d\n",dist[1]);
	printf("*********************************\n");
	*/
	found  = FALSE;
	visited[i] = 1;//表示第i个顶点已经遍历过其邻接边
	while(!found) {
		//在所有尚未求得最短路径的顶点中求使dist[i]取得最小值的i值
		min = MinVal(g,dist,visited);
		//printf("min=%d\n",min);
		if(min == j) found = TRUE;
		else {
			v = min;
			visited[v] = 1;
			//printf("dist[v]=%d\n",dist[v]);
			p = g.vertices[v].firstarc;
			while(p) {
				w = p->adjvex;
				if(visited[w]!=1&&(dist[v]+p->length)length;					
					copyPath(path[w],path[v]);
					InsertPath(path[w],v,w);
				}
				p = p->nextarc;
			}
		}
	}
	pathLength = dist[j];
	printf("pathLength:%d\n",pathLength);
	OutPath(g,path[j],PathVal);
	printf("\n%s\n",PathVal.cities);
}


你可能感兴趣的:(数据结构)