解决方案中缺少节点(迷宫DFS求解算法)

时间:2015-05-09 20:26:43

标签: java algorithm depth-first-search maze

我的DFS算法在解决方案中缺少节点时出现问题(检查图像)。每次我的算法遇到一个死胡同时都会发生这种情况:节点从堆栈中跳出来,直到找到可用的移动为止,并且永远不会再次重新绑定。有没有一种简单的方法来修复它而无需重新实现整个算法?

Few missing nodes in solution are marked with red arrow

    final int start = maze.getStart();
    final int stop = maze.getStop();
    final int columns = maze.getColumns();
    final int[] moves = { 0, 1, 2, 3 }; //North, E, S, W
    int position = start;

    Maze.Cells cells = maze.getCells();
    cells.setVisited(position);
    Stack<Integer> stack = new Stack<>();
    visitCells:
    while(position != stop){
        boolean[] availableMoves = cells.getAvailableMoves(position); //only visit yet unvisited cells
        for(int move : moves){
            if(availableMoves[move] && maze.isMovePossible(position, move)){
                position = doMove(position, move)
                cells.setVisited(position);
                stack.push(position);
                continue visitCells;
            }
        }
        position = stack.pop();
    }
    return stack;

我希望代码是可以解释的。绘图算法是正确的,所以我不在这里发布。不要犹豫,在评论中要求提供更多信息。

1 个答案:

答案 0 :(得分:2)

我认为问题在于当你从A移动到B时,你将新的位置B推到堆栈上。这意味着当你回溯时,你永远不会回到A。

尝试重新排序:

            position = doMove(position, move)
            cells.setVisited(position);
            stack.push(position);

            stack.push(position);
            position = doMove(position, move)
            cells.setVisited(position);