最短路径算法的修改(从节点到自身的路由)
我正在应用全对最短路径算法(Floyd-Warshall )到这个有向图:
该图由其邻接矩阵表示。简单的代码如下所示:
public class ShortestPath {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
int [][] adj= {
{0, 6, x, 6, 7},
{x, 0, 5, x, x},
{x, x, 0, 9, 3},
{x, x, 9, 0, 7},
{x, 4, x, x, 0}};
int [][] D = adj;
for (int k=0; k<5; k++){
for (int i=0; i<5; i++){
for (int j=0; j<5; j++){
if(D[i][k] != x && D[k][j] != x && D[i][k]+D[k][j] < D[i][j]){
D[i][j] = D[i][k]+D[k][j];
}
}
}
}
//Print out the paths
for (int r=0; r<5; r++) {
for (int c=0; c<5; c++) {
if(D[r][c] == x){
System.out.print("n/a");
}else{
System.out.print(" " + D[r][c]);
}
}
System.out.println(" ");
}
}
}
就算法而言,上面的代码工作得很好。
我试图表明从任何节点到自身的路径不一定一定是0
,正如这里使用邻接矩阵所暗示的那样,但可以是任何可能的路径其他节点:例如 B -...-...-...-B
有没有办法修改我当前的表示以指示从 B< /code> 到
B
,不是零,而是 12
,遵循 BCEB
路线?可以通过某种方式修改邻接矩阵方法来完成吗?
I am applying the all-pairs shortest path algorithm (Floyd-Warshall) to this directed graph:
The graph is represented by its adjacency matrix. The simple code looks like this:
public class ShortestPath {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
int [][] adj= {
{0, 6, x, 6, 7},
{x, 0, 5, x, x},
{x, x, 0, 9, 3},
{x, x, 9, 0, 7},
{x, 4, x, x, 0}};
int [][] D = adj;
for (int k=0; k<5; k++){
for (int i=0; i<5; i++){
for (int j=0; j<5; j++){
if(D[i][k] != x && D[k][j] != x && D[i][k]+D[k][j] < D[i][j]){
D[i][j] = D[i][k]+D[k][j];
}
}
}
}
//Print out the paths
for (int r=0; r<5; r++) {
for (int c=0; c<5; c++) {
if(D[r][c] == x){
System.out.print("n/a");
}else{
System.out.print(" " + D[r][c]);
}
}
System.out.println(" ");
}
}
}
The above works fine as far as the algorithm is concerned.
I am trying to indicate that a path from any node to itself is not necessarily 0
, as implied by the use of the adjacency matrix here, but can be any possible path through other nodes: For example B -...-...-...-B
Is there a way to modify my current representation to indicate that a shortest path from say, B
to B
, is not zero, but 12
, following the B-C-E-B
route? Can it be done by somehow modifying the adjacency matrix method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将对角元素邻接矩阵从 0 更改为无穷大(理论上)应该可行。
这意味着自循环成本是无限的,任何其他小于该成本的路径都更好,因此如果存在从节点到自身的路径,通过其他节点,其成本将是有限的,它将取代无限值。
实际上,您可以使用整数的最大值作为无限。
Changing the diagonal elements adjacency matrix from 0 to infinity (theoretically) should work.
It means the self loop cost is infinite and any other path with less than this cost is better hence if a path exists from a node to itself, through other nodes, its cost will be finite and it will replace the infinite value.
Practically you can use maximum value of integer as infinite.