码迷,mamicode.com
首页 > 编程语言 > 详细

Floyd_Warshall算法

时间:2017-10-25 23:38:46      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:nbsp   out   rom   return   ini   main   代码   iostream   exist   

      Floyd_Warshall算法主要用于求解所有节点对的最短路径,代码如下:

#include<iostream>

using namespace std;

#define Inf 65536;
#define NIL -1;

int N = 5;  //假定图的节点有5个
int map[6][6];   //为方便,节点从1开始标号,该矩阵存储权重
int dist[6][6][6];
int path[6][6][6];

void Init()  //构建邻接矩阵
{
	for (int i = 1; i <= N; i++)
	{
		for (int j = 1; j <= N; j++)
		{
			if (i == j)
			{
				map[i][j] = 0;
			}
			else
				map[i][j] = Inf;
		}
	}
	map[1][2] = 3, map[1][3] = 8, map[1][5] = -4;
	map[2][4] = 1, map[2][5] = 7;
	map[3][2] = 4;
    map[4][1] = 2, map[4][3] = -5;
	map[5][4] = 6;
	


}

void Floyd_Warshall()
{
	for (int i = 1; i <= N; i++)
	{
		for (int j = 1; j <= N; j++)
		{
			dist[i][j][0] = map[i][j];
			path[i][j][0] = NIL;
		}
	}
	path[1][2][0] = 1, path[1][3][0] = 1, path[1][5][0] = 1;
	path[2][4][0] = 2, path[2][5][0] = 2;
	path[3][2][0] = 3;
	path[4][1][0] = 4, path[4][3][0] = 4;
	path[5][4][0] = 5;
	for (int k = 1; k <= N; k++)
	{
		for (int i = 1; i <= N; i++)
		{
			for (int j = 1; j <= N; j++)
			{
				if (dist[i][j][k - 1] <= dist[i][k][k - 1] + dist[k][j][k - 1])
				{
					dist[i][j][k] = dist[i][j][k - 1];
					path[i][j][k] = path[i][j][k - 1];
				}
					
				else
				{
					dist[i][j][k] = dist[i][k][k - 1] + dist[k][j][k - 1];
					path[i][j][k] = path[k][j][k - 1];
				}
					
			}
		}
	}
}

void Printf_Path(int path[6][6][6], int i, int j)
{
	if (i == j)
		cout << i << " ";
	else if (path[i][j][N] == -1)
	{
		cout << "NO path from " << i << " to " << j << "exists" << endl;
	}	
	else
	{
		Printf_Path(path, i, path[i][j][N]);
		cout << j << " ";
	}
		
}

int main()
{
	Init();
	Floyd_Warshall();

	for (int k = 0; k <= N; k++)
	{
		for (int i = 1; i <= N; i++)
		{
			for (int j = 1; j <= N; j++)
			{
				cout << dist[i][j][k] << " ";
			}
			cout << endl;
		}
		cout << endl;
	}

	for (int k = 0; k <= N; k++)
	{
		for (int i = 1; i <= N; i++)
		{
			for (int j = 1; j <= N; j++)
			{
				cout << path[i][j][k] << " ";
			}
			cout << endl;
		}
		cout << endl;
	}

	Printf_Path( path, 1, 4);
	return 0;
}

  夜深了,至亲至疏至陌路。

Floyd_Warshall算法

标签:nbsp   out   rom   return   ini   main   代码   iostream   exist   

原文地址:http://www.cnblogs.com/1242118789lr/p/7732519.html

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