dijkstra算法求解最短路径

图1

#include<iostream>
using namespace std;
#define MaxInt 999 //极大值
#define MVNum 100  //最大顶点数
typedef char VertexType;
struct Graph{
	VertexType vexs[MVNum];//顶点表
	int arc[MVNum][MVNum];//邻接矩阵
	int vexnum;//顶点数
};


void Dijkstra_sort(Graph G,int v0)
{
	int n=G.vexnum;
	int Path[n];//记录前驱
	int D[n]; //记录相对最短路径
	bool S[n];//判断当前路径长度是否为最短路径

	for(int i=0;i<n;i++)
	{
		S[i]=false;
		D[i]=G.arc[v0][i];
		if(D[i]<MaxInt)
		Path[i]=v0;
		else 
		Path[i]=-1;
	}
	S[v0]=true;
	D[v0]=0;
	//初始化
	int v;
	for(int i=0;i<n-1;i++)
	{
		int min=MaxInt;
		for(int w=0;w<n;w++)
		{

			if(D[w]<min&&!S[w])
			{
				min=D[w];
				v=w;
			}
			
		}
		S[v]=true;
		for(int w=0;w<n;w++)
		{
			if(!S[w]&&D[w]>(D[v]+G.arc[v][w]))
			{
				D[w]=D[v]+G.arc[v][w];
				Path[w]=v;
			}
		}
	}
	for(int i=0;i<G.vexnum;i++)
	{
		if(i!=v0)
		{
			cout<<v0<<"到"<<i<<"的最短路径="<<D[i]<<endl;
			cout<<"路线为: " ;
			for(int k=i;k!=v0;k=Path[k])
			{	
				cout<<k<<"<---";
			}
			cout<<v0<<endl;
		}
		
	}        
}

void GradeMap(Graph &G)//创建图1
{
	G.vexnum=5;
	for(int i=0;i<=G.vexnum;i++)
	{
		for(int j=0;j<=G.vexnum;j++)
		{
			G.arc[i][j]=MaxInt;
		}
	}
	G.arc[0][4]=10;
	G.arc[0][2]=30;
	G.arc[0][1]=100;
	G.arc[2][1]=60;
	G.arc[2][3]=60;
	G.arc[3][1]=10;
	G.arc[4][3]=50;
	
	//输出一下
	for(int p=0;p<G.vexnum;p++)
	{
		for(int q=0;q<G.vexnum;q++)
		{
			cout<<G.arc[p][q]<<"\t";
		}
		cout<<endl;
	}
}

int main()
{
	Graph G;
	GradeMap(G);
	Dijkstra_sort(G,0);下标为0的点到其他点的距离
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值