您的位置:首页 > 其它

动态规划的Warshall和Floyd算法:

2015-06-04 21:10 169 查看
Warshall算法



简单的讲就是



伪代码:



代码:

package Section8;

/*第八章 动态规划   有向图传递闭包的Warshall算法*/

public class Warshall {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] AdjMat = {
{0,1,0,0},
{0,0,0,1},
{0,0,0,0},
{1,0,1,0}
};

int[][] BiBao = Warshall(AdjMat);

System.out.println("输出表达传递闭包的矩阵:\n");
for(int i = 0;i < BiBao.length;i++)
{
for(int j = 0;j < BiBao.length;j++)
System.out.print(BiBao[i][j] + "  ");
System.out.println();
}
}

public static int[][] Warshall(int[][] AdjMat){
//接受一个图的邻接矩阵为参数,返回表达它的传递闭包的矩阵
int[][] Rresult = AdjMat;        //初始结果R0
int n = AdjMat.length;

for(int k = 0;k < n;k++)    //R0到Rn,做n步变换
{
int[][] Rtemp = new int

;    //每循环一下求下次结果
for(int i = 0;i < n;i++)
for(int j = 0;j < n;j++)
{
if(Rresult[i][j] == 1)
Rtemp[i][j] = 1;
else if(Rresult[i][k] == 1 && Rresult[k][j] == 1)
Rtemp[i][j] = 1;
else Rtemp[i][j] = 0;
}
Rresult = Rtemp;
}

return Rresult;
}

}


时间复杂度为n^3,空间复杂度是n^2。

Floyd算法:Floyd算法可以用于构造无向或有向加权图(不包含长度为负的回路)的完全最短路径:

与Warshall算法基本相同:

伪代码



代码:

package Section8;

/*第八章 动态规划   完全最短路径的Floyd算法*/

public class Floyd {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] WeightMat = {
{0,1000,3,1000},
{2,0,1000,1000},
{1000,7,0,1},
{6,1000,1000,0}
};
int[][] Result = Floyd(WeightMat);

System.out.println("输出表达完全最短路径的矩阵:\n");
for(int i = 0;i < Result.length;i++)
{
for(int j = 0;j < Result.length;j++)
System.out.print(Result[i][j] + "   ");
System.out.println();
}

}

public static int[][] Floyd(int[][] WeightMat){
//接受一个图的权重矩阵,返回表达完全最短路径的矩阵
int n = WeightMat.length;
int[][] Result = WeightMat;

for(int k = 0;k < n;k++)    //进行n次变换,每次加入第k个点
{
int[][] temp = new int

;
for(int i = 0;i < n;i++)
for(int j = 0;j < n;j++)
temp[i][j] = min(Result[i][j],Result[i][k]+Result[k][j]);//加入第k个点后路径是否能缩短
Result = temp;
}

return Result;
}

private static int min(int m,int n){
if(m  < n)
return m;
return n;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法