2013-11-03 45 views
0

我在执行Floyd-Warshall算法时遇到困难,我试图找出一个自己的项目。我有一组测试数据,但是当我在ShortestPath创建后打印出来时,我只是得到一个null和一个内存地址。不确定从这里开始使用此算法的具体位置。任何援助非常感谢!Floyd-Warshall执行问题

public static void main(String[] args) { 
    int x = Integer.MAX_VALUE; 
    int[][] adj = {{ 0, 3, 8, x, 4 }, 
        { x, 0, x, 1, 7 }, 
        { x, 4, 0, x, x }, 
        { 2, x, 5, 0, x }, 
        { x, x, x, 6, 0 }}; 
    ShortestPath sp = new ShortestPath(adj); 
    System.out.println(sp); 
} 

public class ShortestPath { 

private int[][] adj; 
private int[][] spTable; 
private int n; 

public static void copy(int[][] a, int[][] b) { 
    for (int i=0; i < a.length; i++) 
     for (int j = 0; j < a[0].length; j++) 
      a[i][j] = b[i][j]; 
} 

public ShortestPath(int[][] adj) { 
    n = adj.length; 
    this.spTable = new int[n][n]; 
    copy(this.spTable, adj); 

    for(int k = 0; k < n; k++) { 
     for(int i = 0; i < n; i++){ 
      for(int j = 0; j < n; j++){ 
       if (spTable[i][k] + spTable[k][j] < spTable[i][j]) { 
        spTable[i][j] = spTable[i][k] + spTable[k][j]; 
        adj[i][j] = adj[k][j]; 
       } 
      } 
     } 
    } 
} 


@Override 
public String toString() { 
    return adj + "\n\n" + spTable + ""; 
} 

回答

0
public ShortestPath(int[][] adj) 

参数adj你路过此地被遮蔽的adj类成员 - 你永远不给类成员的值。一个简单的解决方法是把下面的代码行。在上面构造的任何地方:

this.adj = adj; 

更多见this


的另一个问题是在这里:

return adj + "\n\n" + spTable + ""; 

您不能只是将其添加到字符串数组中的打印值 - 将只打印地址。

您需要一个双重循环来打印数组中的值。有关更多详细信息,请参阅this question