【问题标题】:Floyd/Warshall Algorithm reconstructing a path, saving into a listFloyd/Warshall 算法重建路径,保存到列表中
【发布时间】:2012-05-11 00:36:49
【问题描述】:

两个简单的问题,我的大脑无法正常工作。我正在使用弗洛伊德算法并尝试重建从顶点 U 到顶点 V 的路径。 这是我重建路径的代码。

public List<Integer> findCheapestPath(int u, int v)
{
    if (u >= adjMatrix.length || v >= adjMatrix.length || u < 0 || v < 0)
    {
        throw new IllegalArgumentException("Error--Illegal Arugment Exception: One of the verticies are not valid.");
    }
    int intermediate;

    intermediate = path[u][v];
    if (intermediate == -1)
    {
        pathList.add(u);
        return pathList;
    } else
    {
        findCheapestPath(u, intermediate);
        findCheapestPath(intermediate, v);
    }
    return pathList;
}

举个例子,令 u = 0 和 v = 3,并设从 0 到 3 的最短路径为 0,1,2,3。 但是我有两个问题。我的 pathList 是该类的实例变量,并且:

  1. 我希望列表返回“0,1,2,3”,但它只返回“0,1,2”,或者如果我将 pathList.add(u) 替换为 pathList.add(v),那么它返回 只有“1,2,3”我不知道如何让它返回整个 包括两个端点的路径。试图把 pathList.add(other vertex) 将导致它复制每个中间顶点。
  2. 当我再次调用该方法时,让 u = 3 和 v = 0,并让从 3 到 0 的最短路径为“3,0”(已经是最短路径),它 只是添加到我以前的列表中,使其 上面出现我的错误 "0,1,2,3" 或 "1,2,3,0" 当它应该只是 "3,0" 时

有什么帮助吗?

【问题讨论】:

    标签: list path shortest-path floyd-warshall


    【解决方案1】:

    不要使用类变量,而是做一个包装函数。

    更详细地说,将您的函数更改为此签名:

    private List<Integer> findCheapestPathInner(int u, int v, pathList)
    

    (显然还更改了其中的递归调用以适应新签名),并创建另一个函数:

    public List<Integer> findCheapestPath(int u, int v) {
      List<Integer> pathList = new ArrayList<Integer>();
      pathList.add(u);
      return findCheapestPathInner(u, v, pathList);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-12
      • 2017-09-12
      • 1970-01-01
      • 2011-05-30
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多