Dijkstra算法

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<stack>
using namespace std;
#define MAX_VERTEX_NUM 20
#define INFINITY 32768
int visited[100];
int path[MAX_VERTEX_NUM];
typedef struct node1
{
	int adj;
}gra;
typedef struct node2
{
	gra arcs[100][100];
	int vertex[100];
	int vexnum,arcnum;
}*graph,graph1;
int locatevertex(graph &g,int v)
{
	int j=0,k;
	for(k=0;k<g->vexnum;k++)
	{
		if(g->vertex[k]==v)
		{
			j=k;
			break;
		}	
	}
	return j;
}
void create(graph &g)
{
	int i,j,k,v1,v2,weight;
	printf("请输入图的最大顶点数和最大弧数: ");
	scanf("%d%d",&g->vexnum,&g->arcnum);
	for(i=0;i<g->vexnum;i++)
	{
		for(j=0;j<g->vexnum;j++)
		{
			if(i==j)
			g->arcs[i][j].adj=0;
			else
			g->arcs[i][j].adj=INFINITY;
		}
	}
	printf("请输入图的各顶点值: ");
	for(i=0;i<g->vexnum;i++)
		scanf("%d",&g->vertex[i]);
	for(k=0;k<g->arcnum;k++)
	{
		printf("请输入两顶点1,2表示1到2有关系: ");
		scanf("%d%d%d",&v1,&v2,&weight);
		i=locatevertex(g,v1);
		j=locatevertex(g,v2);
		g->arcs[i][j].adj=weight;
	}
}
void shortestpath(graph &g,int n)
{
	int v0=0,k,min;
	int dist[MAX_VERTEX_NUM];
    bool S[MAX_VERTEX_NUM];
	for(int i=0;i<g->vexnum;i++)
	{
		S[i]=false;//对S初始化
		dist[i]=g->arcs[v0][i].adj;//对dist初始化
		if(dist[i]<INFINITY)
		path[i]=0;
		else
		path[i]=-1;
	}
	S[v0]=true;
	for(int t=1;t<=g->vexnum-1;t++)
	{
		min=INFINITY;
		for(i=0;i<g->vexnum;i++)
		{
			if(!S[i]&&dist[i]<min)
			{
			 min=dist[i];
             k=i;
			}
		}
			if(min==INFINITY)
			return ;
		for(i=0;i<g->vexnum;i++)
		{
			if(!S[i]&&g->arcs[k][i].adj!=INFINITY&&(dist[k]+g->arcs[k][i].adj<dist[i])&&k!=i)
			{
				dist[i]=dist[k]+g->arcs[k][i].adj;
				path[i]=k;
			}
		}
		S[k]=true;
	}
	n=locatevertex(g,n);
	int x=n;
	while(n>=0)
	{
		printf("%d ",path[n]);
		if(path[n]==0)
		break;
		n=path[n];
	}
	printf("最短路径长度为: ");
	printf("%d\n",dist[x]);
}
int main()
{
	graph g;
	int n;
	g=(graph)malloc(sizeof(graph1));
	create(g);
	printf("请输入一个顶点求出它的最短路径: ");
	scanf("%d",&n);
	shortestpath(g,n);
	return 0;
}

你可能感兴趣的:(dijkstra算法)