/**
* 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();
}
}
动态规划——3 floyd算法
最新推荐文章于 2022-12-02 16:29:19 发布