第4章 贪心算法,Dijkstra算法(邻接矩阵存储,时间复杂度为O(n^2))

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

#define MAXSIZE 100
#define INF 999999999

int weight[MAXSIZE][MAXSIZE];	//边的权值
int shortest[MAXSIZE];			//源点到每个点的最短路径长度
bool vis[MAXSIZE];				//顶点访问标记
int preV[MAXSIZE];				//最短路径

int Dijkstra(int n, int src, int dest)
{
	memset(vis, false, sizeof(vis));
	int i;
	for (i = 1; i <= n; i++)
	{
		shortest[i] = INF;
	}
	shortest[src] = 0;
	preV[src] = 0;

	for (i = 1; i <= n; i++)
	{
		int minV = INF;
		int x, y;
		//挑选出未访问且路径长度最短的顶点
		for (y = 1; y <= n; y++)
		{
			if (!vis[y] && shortest[y] < minV)
			{
				minV = shortest[x = y];
			}
		}
		vis[x] = true;	//该顶点标记为已访问
		
		for (y = 1; y <= n; y++)
		{
			//经过x顶点到y顶点是否路径更短
			if (shortest[x]+weight[x][y] < shortest[y])
			{
				shortest[y] = shortest[x]+weight[x][y];
				preV[y] = x;	//到y的最短路径上,y的前一个顶点为x
			}
		}
	}
	return shortest[dest];
}

void InitGraph(int n)
{
	int i, j;
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= n; j++)
		{
			weight[i][j] = INF;
		}
	}
}

int main(void)
{
	int n, m;
	while (scanf("%d%d", &n, &m) != EOF)
	{
		InitGraph(n);
		int i;
		for (i = 0; i < m; i++)
		{
			int v1, v2, w;
			scanf("%d%d%d", &v1, &v2, &w);
			weight[v1][v2] = weight[v2][v1] = w;
		}
		int src, dest;
		scanf("%d%d", &src, &dest);

		printf("%d\n", Dijkstra(n, src, dest));
		for (i = dest; i != 0; i = preV[i])
		{
			printf("%d ", i);
		}
		putchar('\n');
	}
	return 0;
}

/*
7 12
1 2 2
1 3 5
1 4 7
2 3 4
2 5 7
3 4 1
3 5 9
3 6 6
4 6 3
5 6 2
5 7 5
6 7 4
*/

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