最短路径之djikstra algorithm

dijkstra最短路径作为一种单源最短路径问题,其主要思想就是依次找出与初始顶点相连最短连通路,之后更新与其他顶点vertex路径。编码时首先弄一个数组记录开始顶点到另一其他点的路径距离如weights2othPts[MAXNUM],之后依次选取最小的路径更新,同时用个mark数组登记每次用到的顶点,用一张图表示就是:



Main algorithm steps for dijkstra shortest path:

while(not complete) do the following steps from a to d

a)find vertex j such that it has minmum distance among those vertices yet not enumerated(枚举)

b)make Mark[j]=1

c)vary i from 1 to n do the following steps (i) and (ii)

i)if(Mark[i]=1)

i++;

ii)check if adjacentMatrix[j][i] is not 0

if so do the following:

if(weights2othPts[j]+adjacentMatrix[j][i]<weights2othPts[i])

weights2othPts[i]=weights2othPts[j]+adjacentMatrix[j][i];//update 更新

PATH[i]=j

d)complete==true? quit?or continue


implementation using c:(c处理代码)


int search(int *pt2arr,int *pt2mk,int n)
{
	int i,v,min=INF;
	for(i=0;i<n;i++)
	{
		if(*(pt2mk+i)==0)
			if(*(pt2arr+i)<=min)	//若跟StartN顶点没有相连的而且最后还没有更新则用<=
			{
				v=i;
				min=*(pt2arr+i);
			}
	}
	return v;
}

void dijkstra_shortest_path(int a[][25],int LEN,int StartN)//输入邻接矩阵a,以及顶点数LEN,以及开始顶点StartN
{
	int i,j,Mark[25],weights2othPts[25];
	char str[25],tmp[25],path[25][25];
	for(i=0;i<LEN;i++)				//设置初始顶点到其它顶点开始标识为0
		Mark[i]=0;

	for(i=0;i<LEN;i++)
	{
		if(a[StartN][i]==0)
		{
		weights2othPts[i]=INF;
		strcpy(path[i],"-");
		}
		else
		{
		weights2othPts[i]=a[StartN][i];
		itoa(StartN,str,10);
		strcpy(path[i],str);
		strcat(path[i],"-");
		itoa(i,str,10);
		strcat(path[i],str);
		}
	}
	Mark[StartN]=1;//标识开始顶点为1
	weights2othPts[StartN]=0;//把自己到自己的设为0
	int flag=0;

	while(!flag)				//开始进入dijkstra算法 entering the dijkstra algorithm module
{
	j=search(weights2othPts,Mark,LEN);
	Mark[j]=1;
	i=0;
	while(i<LEN)
	{
			if(a[j][i])//若a[j][i]不为0,亦即从与StartN出发最短点j再出发的j-i路径不能为0(即没连通)
			
				if(weights2othPts[j]+a[j][i]<weights2othPts[i])
				{
					weights2othPts[i]=weights2othPts[j]+a[j][i];
					strcpy(path[i],path[j]);
					strcat(path[i],"-");
					itoa(i,str,10);
					strcat(path[i],str);
				}
		i++;
	}
	printf("weights to other vertexs:\n");
	for(i=0;i<LEN;i++)
		printf("%d\t",weights2othPts[i]);
	printf("\nPath matrix:\n");
	for(i=0;i<LEN;i++)
		printf("%s\t",path[i]);
	printf("\nthe out is j=%d\n",j);
	i=0;
	while(Mark[i++]);
	if(i>LEN)flag=1;			//若Mark中前LEN都为1了那说明dijkstra搜索已完毕可以退出
}
printf("weights to other vertexs:\n");
	for(i=0;i<LEN;i++)
		printf("%d\t",weights2othPts[i]);
	printf("\nPath matrix:\n");
	for(i=0;i<LEN;i++)
		printf("%s\t",path[i]);
	printf("\nthe out is j=%d\n",j);
}

测试数据:(testing data)

sample input:
4


0 1 3 0
0 0 1 4
0 0 0 2
0 2 0 0


0           //here is the starting no. of vertex,输入为单源顶点如0顶点,到自身为0
sample output:
0 1 24




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值