深度优先搜索以查找节点之间的所有路径问题

时间:2017-08-24 11:55:38

标签: java algorithm recursion dfs

我一直在努力解决这个深度优先搜索问题,但我无法弄明白。我想打印所有路径,但不知何故它只打印一些路径。我可以在这里找出这么长时间的错误:

  void printAllPathsUtil(Vertex v, Vertex d, ArrayList<Vertex> path){

        v.state = VISITED;
        path.add(v);

        if (v == d) {
            for (Vertex p : path) {
                System.out.print("Print: " + p.value + " ");
            }
            System.out.println();
        }
        else {
            for (Vertex city : v.outboundCity){

                if (city.state == UNVISITED) {

                    printAllPathsUtil(city, d, path);
                }
            }
        }
        path.remove(v);
        v.state = UNVISITED;
    }


    void printAllPaths(Vertex v, Vertex u){
        clearStates();
        ArrayList<Vertex> path = new ArrayList<>();
        printAllPathsUtil(v, u, path);
    }

Vertex Class是这样的:

public class Vertex{
String value;

Vertex previous = null;
int minDistance = Integer.MAX_VALUE;

List<Vertex> inboundCity;
List<Vertex> outboundCity;
State state;
}

1 个答案:

答案 0 :(得分:1)

我认为你应该在loop

中包含这两行
path.remove(v);
v.state = UNVISITED;

你应该从路径中删除顶点并在递归终止后立即“取消访问”它们,而不是在你结束循环时