首页 > 其他 > 详细

动态规划——2 Warshall算法

时间:2014-01-21 22:59:48      阅读:423      评论:0      收藏:0      [点我收藏+]
/**
 * Floyd算法<br/>
 * 计算完全最短路径<br/>
 * k >= 0, Dij(0) = Wij, Dij(k) = min{Dij(k-1), Dik(k-1) +Dkj(k-1)} <br/>
 * 
 * O(n^3)
 * @author chenxuegui
 * 
 */
public class Floyd
{
	static final int max = 10000;

	public static void main(String[] args)
	{

		int[][] n = new int[][] { { 0, max, 3, max }, { 2, 0, max, max },
				{ max, 7, 0, 1 }, { 6, max, max, 0 } };

		warshall(n);

	}

	/**
	 * 
	 * @param n
	 */
	public static void warshall(int[][] n)
	{
		for (int k = 0; k < n.length; k++)
		{

			print(n);
			for (int i = 0; i < n.length; i++)
			{

				for (int j = 0; j < n.length; j++)
				{
					n[i][j] = Math.min(n[i][j], n[i][k] + n[k][j]);

				}
			}
		}

		print(n);
	} 

	public static void print(int[][] n)
	{
		for (int i = 0; i < n.length; i++)
		{
			for (int j = 0; j < n.length; j++)
			{
				if (n[i][j] >= 10000)
				{
					System.out.print("max ");
				}
				else
				{
					System.out.print(n[i][j] + " ");
				}
			}

			System.out.println();
		}

		System.out.println();
	}
}


动态规划——2 Warshall算法

原文:http://blog.csdn.net/chenxuegui1234/article/details/18601795

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!