邻接表实现Dijkstra最短路径算法

#include <iostream>
#define INF 9999
using namespace std;
struct node
{
	int node,next;
	int weight;
}edge[10000];
int first_arc[300],cnt;
void addEdge(int x,int y,int w)
{
	edge[cnt].node=y;
	edge[cnt].next=first_arc[x];
	first_arc[x]=cnt;
	edge[cnt].weight=w;
	++cnt;
}
int main()
{
	int n,m,u,v,w,start;
	cin>>n>>m>>start;
	for(int i=0;i<n;++i)
        first_arc[i]=-1;
	for(int i=0;i<m;++i)
	{
		cin>>u>>v>>w;
		addEdge(u,v,w);
	}
	int dist[100],s[100],path[100];
	for(int i=0;i<n;++i)
	{
		dist[i]=INF;
		s[i]=0;
		path[i]=-1;
	}
	int p=first_arc[start];
	while(p!=-1)
	{
		dist[edge[p].node]=edge[p].weight;
		path[edge[p].node]=start;
		p=edge[p].next;
	}
	s[start]=1;
	path[start]=0;
	int min_dist,k;
	for(int i=0;i<n;++i)
	{
	   	min_dist=INF;
	   	for(int j=0;j<n;++j)
	   	   if(s[j]==0&&dist[j]<min_dist)
	   	   {
	   	   	  k=j;
	   	   	  min_dist=dist[j];
	   	   }
	   	s[k]=1;
	   	p=first_arc[k];
	   	while(p!=-1)
		{
			int t=edge[p].node;
			if(s[t]==0&&dist[k]+edge[p].weight<dist[t])
			{
				dist[t]=dist[k]+edge[p].weight;
                path[t]=k;
			}
			p=edge[p].next;
		}
	}
	int output[100],out_cnt,t;
	for(int i=0;i<n;++i)
	   if(s[i]==1&&i!=start)
	   {
		    cout<<start<<" to "<<i<<" with length "<<dist[i]<<" :";
		   	out_cnt=0;
		   	output[out_cnt]=i;
		   	t=path[i];
		   	if(t==-1)
		   	   cout<<"no path"<<endl;
		   	else
		    {
		    	while(t!=start)
		    	{
		    		++out_cnt;
		    		output[out_cnt]=t;
		    		t=path[t];
		    	}
		    	++out_cnt;
		    	output[out_cnt]=start;
		    	cout<<output[out_cnt];
		    	for(int j=out_cnt-1;j>=0;--j)
		    	   cout<<','<<output[j];
		    	cout<<endl;
		    }
	   }
}

测试数据:

7 12 0
0 1 4
0 3 6
0 2 6
1 4 7
1 2 1
3 2 2
3 5 5
2 4 6
2 5 4
4 6 6
5 4 1

5 6 8

输出:

0 to 1 with length 4 :0,1
0 to 2 with length 5 :0,1,2
0 to 3 with length 6 :0,3
0 to 4 with length 10 :0,1,2,5,4
0 to 5 with length 9 :0,1,2,5
0 to 6 with length 16 :0,1,2,5,4,6

参考 数据结构教程/李春葆主编.—4版.—北京:清华大学出版社,2013.1

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/qq920444182/article/details/79603410
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞