码迷,mamicode.com
首页 > 其他好文 > 详细

Dijkstra

时间:2019-11-14 09:25:53      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:path   算法   pre   str   jks   isp   mat   路径   max   

Dijkstra算法

void Dijkstral(MatGraph g, int v)
{
	int i, j, u;
	int mindist;
	int path[MAXV], dist[MAXV], S[MAXV];
	for (i = 0; i < g.n; i++)
	{
		S[i] = 0;
		dist[i] = g.edges[v][i];
		if (g.edges[v][i] < INT_MAX)
			path[i] = v;
		else
			path[i] = -1;
	}
	S[v] = 1;
	path[v] = 0;
	for (i = 1; i < g.n; i++)
	{
		mindist = INT_MAX;
		for (j = 0; j < g.n; j++)
		{
			if (S[j] == 0 && dist[j] < mindist)
			{
				u = j;
				mindist = dist[j];
			}
		}
		S[u] = 1;
		for (j = 0; j < g.n; j++)
		{
			if (S[j] == 0)
			{
				if (g.edges[u][j] < INT_MAX && dist[u] + g.edges[u][j] < dist[j])
				{
					dist[j] = dist[u] + g.edges[u][j];
					path[j] = u;
				}
			}
		}
	}
	Dispath(g, dist, path, S, v);
}

  

void Dispath(MatGraph g, int dist[], int path[], int S[], int v)
{
	int i, j, k;
	int apath[MAXV], d;
	for (i = 0; i < g.n; i++)
	{
		if (S[i] == 1 && i != v)
		{
			printf("顶点%d到顶点%d的路径长度为:%d\t路径为:",v, i, dist[i]);
			d = 0;
			apath[d] = i;
			k = path[i];
			if (k == -1)
				printf("无路径\n");
			else
			{
				while (k != v)
				{
					apath[++d] = k;
					k = path[k];
				}
				apath[++d] = v;
				printf("%d", apath[d]);
				for (j = d - 1; j >= 0; j--)
					printf(",%d", apath[j]);
				printf("\n");
			}
			
		}
	}
}

  

Dijkstra

标签:path   算法   pre   str   jks   isp   mat   路径   max   

原文地址:https://www.cnblogs.com/KIROsola/p/11854512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!