(Dijkstra) entry Dykstra method

About this algorithm I think there are several important steps

1. First is selected from the set point is 0
2 and set a flag bit array, the initial value of all points are set to false, which is not accessed, had once visited, will be as incorporated into point visited the set
3. how to start using the cycle, the next point of the distance determination (determination that has not been visited and his distance less than the current minimum distance), to choose the smallest point, which access is not set to true
distance after 4 update, the update condition is that the current position is greater than the distance from the first point is the latest marker distance from the point to point to true plus the latest point is marked as true to the original point distance
the loop iterates until the end

#include<stdio.h>
#define MAX 100
#define INF 1000000000
int map[MAX][MAX];
int dis[MAX];//距离的数组
bool mark[MAX];//记录被选中的结点 
int n;
void dijkstra(int s)//求s点到各结点的最短距离 
{
	int k;
	for(int i=0;i<n;i++)//初始化所有的结点都没有被选中 
		mark[i]=false; 
	for(int i=0;i<n;i++)//将每个结点到s结点的距离放入dis数组
		dis[i]=map[s][i];//map这个二维数组是统计两点的距离,左边是起点,右边是终点,//最后是值
	mark[s]=true;//s结点被选中 
	dis[s]=0;//将s结点的距离被设为0 
	int min;//最短距离
	for(int i=1;i<n;i++)//一共n-1次
	{
		min=INF;//找当前最小值
		for(int j=0;j<n;j++)
		{
			if(!mark[j]&&dis[j]<min)//这个是判断条件
			{
				min=dis[j];
				k=j;
			}
		}
		mark[k]=true;//k结点被选中
		for(int j=0;j<n;j++)//开始更新距离
		{
			if(!mark[j]&&(dis[j]>dis[k]+map[k][j]))
				dis[j]=dis[k]+map[k][j];
		} 
	}	
}
int main()
{
	int m,start,end;
	int a,b,c;
	printf("请分别输入顶点和边的数目:"); 
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
			map[i][j]=INF;//相当于是初始化各个点的距离
	for(int i=0;i<m;i++)
	{
		printf("请输入第%d个边的起始点、终点和距离:",i+1);
		scanf("%d %d %d",&a,&b,&c);
		if(c<map[a][b]||c<map[b][a])//其实这个条件我感觉可有可无,直接赋值即可
		{
			map[a][b]=c;
			map[b][a]=c;
		}
	}
	printf("请输入源结点和目标结点:");
	scanf("%d %d",&start,&end);
	dijkstra(start);
	printf("结点%d到%d的最短路径长度为:%d\n",start,end,dis[end]);
}

Published 72 original articles · won praise 5 · Views 2822

Guess you like

Origin blog.csdn.net/qq_41115379/article/details/104877906