DFS递归,重新访问节点,即使在被标记为已访问之后也是如此

时间:2015-07-28 15:34:45

标签: java recursion depth-first-search

所以,我一直在尝试使用递归来运行这个简单的DFS代码,并且已经将已经节点标记为已访问,但它仍然在被访问的节点周围循环,所以我注意到了布尔数组{{1在每个递归步骤中再次创建,并且我无法将该数组放在该方法之外,并在该方法中使用它。任何帮助,将不胜感激! :)

isVisited

编辑: 好吧,感谢答案中提供的技巧,我能够修复代码,现在它似乎也在处理更新的测试用例,但在某种程度上它似乎仍然是错误的,假设我给代码一个图形以下边缘:
(终点1)(终点2)
1 2
1 3
2 3
2 4
3 5
4 5
4 6
5 6

如果我从节点1到5搜索DFS,我得到的答案是1-> 2-> 3-> 5,这是一个有效的路径,但可能会更深入1 - > 2-> 4-> 6-> 5路径,是不是DFS应该做什么?旅行的深度?

新守则:

private boolean hasRoutesDFS(int start, int end) {
    if (start < 0 || start > graph.size() || end < 0 || end > graph.size())
        return false;
    boolean[] isVisited = new boolean[graph.size() + 1];

    if (start == end)
        return true;
    else{
         isVisited[start]=true;
        System.out.print(start + "->");
        for (int v : graph.getEdge(start)) {
            if (!isVisited[v] ) {
                isVisited[v] = true;
                hasRoutesDFS(v, end);
            }
        }

    }

    return false;
}

1 个答案:

答案 0 :(得分:1)

The standard trick to make a recursive function use static data is to pass the static data as a parameter and create it from the base signature.

private boolean hasRoutesDFS(int start, int end) {
    return hasRoutesDFS(start, end, new boolean[graph.size() + 1]);
}

private boolean hasRoutesDFS(int start, int end, boolean[] isVisited) {
    if (start < 0 || start > graph.size() || end < 0 || end > graph.size()) {
        return false;
    }

    if (start == end) {
        return true;
    } else {
        isVisited[start] = true;
        System.out.print(start + "->");
        for (int v : graph.getEdge(start)) {
            if (!isVisited[v]) {
                isVisited[v] = true;
                hasRoutesDFS(v, end, isVisited);
            }
        }

    }

    return false;
}

Not suggesting in any way that the rest of your code is correct (it actually looks wrong to me). Just showing you how to avoid the problem you are seeing wit a new array being created at each call.