算法设计-Dijkstra

#include<iostream>
#include<stdio.h>
#include<malloc.h>
#define INF 32767
#define MAXV 5
using namespace std;

typedef char InfoType;

typedef struct
{
	int no;
	InfoType info;
}VertexType;
typedef struct
{
	int edges[MAXV][MAXV];
	int n,e;
	VertexType vexs[MAXV];
}MatGraph;

void CreateMat(MatGraph &g,int A[MAXV][MAXV],int n,int e)
{
	int i,j;
	g.n=n;g.e=e;
	for(i=0;i<g.n;i++)
	{
		for(j=0;j<g.n;j++)
		{
			g.edges[i][j]=A[i][j];
		}
	}
}

void DispMat(MatGraph g)
{
	int i,j;
	for(i=0;i<g.n;i++)
	{
		for(j=0;j<g.n;j++)
		{
			if(g.edges[i][j]!=INF)
			    cout<<" "<<g.edges[i][j]<<" ";
            else
                cout<<" "<<"…";
		}
		cout<<endl;
	}
}

void Dijkstra(int n,int u,float dist[],int p[],int C[5][5])
{
	bool s[n];
	int i,j;
	for(i=0;i<n;i++)
	{
		dist[i]=C[u][i];
		s[i]=false;
		if(dist[i]==INF) p[i]=-1;
		else p[i]=u;
	}
	dist[u]=0;
	s[u]=true;
	for(i=0;i<n;i++)
	{
		float temp=INF;
		int t=u;
		for(j=0;j<n;j++)
		{
			if((!s[j])&&(dist[j]<temp))
			{
				t=j;
				temp=dist[j];
			}
		}
		if(t==u) break;
		s[t]=true;
		for(j=0;j<n;j++)
		{
			if((!s[j])&&C[t][j]<INF)
			{
				if(dist[j]>(dist[t]+C[t][j]))
				{
					dist[j]=dist[t]+C[t][j];
					p[j]=t;
				}
			}
		}
	}
	cout<<"源点1到2-5的最短路径分别为:";
	for(i=1;i<n;i++)
	{
		cout<<dist[i]<<" "; 
	}
	cout<<endl;
}

int main()
{
	MatGraph g;
	int A[MAXV][MAXV]=
	{
		{0,10,INF,30,100},{INF,0,50,INF,INF},{INF,INF,0,INF,10},
		{INF,INF,20,0,60},{INF,INF,INF,INF,0}
	};
	int n=5,e=7;
	int visited[5];
	for(int i=0;i<5;i++)
	    visited[i]=0;
	CreateMat(g,A,n,e);
	cout<<"邻接矩阵为:"<<endl;
	DispMat(g);
	float dist[4]={0,0,0,0};
	int p[4]={0,0,0,0};
	Dijkstra(n,0,dist,p,A);
	return 0;
}

仅作留档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值