动态规划——2 Warshall算法

/**
 * 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算法

上一篇:百度云存储教程---免费建立自己的静态站点


下一篇:CRichedit在结尾添加一行,同时设置字体,大小及颜色,并在添加后自动滚屏到末行,