C中迷宫求解器的递归回溯算法不回溯并被卡住

时间:2020-11-01 02:59:35

标签: c multidimensional-array recursive-backtracking

我试图用C编写一个程序,该程序跟踪迷宫求解器的递归回溯算法的整个搜索过程。因此,我将打印出每个步骤。迷宫是一个简单的迷宫,用“#”代表墙壁“。”。代表空白单元格,“ @”代表初始起点。给定一个起点,我们必须到达迷宫的任何边缘才能完成它。我的搜索算法首先尝试搜索北,东,南,西的路径。 (我将其用作参考:http://www.cs.bu.edu/teaching/alg/maze/

输入给定迷宫的示例:

#######
###.###
###.###
...@..#
###.###
###.###
#######

我的代码试图做什么/输出:

//step 1
#######
###.###
###.###
...+..#
###.###
###.###
#######

//step 2
#######
###.###
###+###
...+..#
###.###
###.###
#######

//Step 3
#######
###+###
###+###
...+..#
###.###
###.###
#######

//Step 4
#######
###X###
###+###
...+..#
###.###
###.###
#######

//step 5
#######
###X###
###X###
...+..#
###.###
###.###
#######

//Step 6
#######
###X###
###X###
...++.#
###.###
###.###
#######
.
. subsequent steps leading to final output
.
.
#######
###X###
###X###
++++XX#
###X###
###X###
#######

这里是我的代码中试图执行此功能的相关示例:

bool is_goal(long row, long col, long m, long n)
{
    if (row == 0 || col == 0 || row == m - 1 || col == n - 1) {
        return true;
    }
    return false;
}
 
bool is_wall(char **maze, long row, long col)
{
   if (maze[row][col] == WALL) {
       return true;
   }
   return false;
}
 
bool find_path(char **maze, char **maze_cpy, long row, long col, long m, long n, long     step)
{
    print_maze(maze_cpy, m, step);
    step += 1;
 
    //Base cases
    if (is_goal(row, col, m, n)) {
        return true;
    }
    if (is_wall(maze, row, col)) {
        return false;
    }
    //used to indicate current cell is part of soln
    maze_cpy[row][col] = '+';
 
    //Recursive cases
    //Go up
    if (find_path(maze, maze_cpy, row - 1, col, m, n, step)) {
        return true;
    }
    //Go right
    if (find_path(maze, maze_cpy, row, col + 1, m, n, step)) {
        return true;
    }
    //Go down
    if (find_path(maze, maze_cpy, row + 1, col, m, n, step)) {
        return true;
    }
    //Go left
    if (find_path(maze, maze_cpy, row, col - 1, m, n, step)) {
        return true;
    }
    //At this point, no solution
    maze_cpy[row][col] = 'X';
    return false;
}

但是,我的输出递归函数仅在第3步停止,我无法弄清为什么它不回溯并更新它已用作不可用路径的路径(带有“ X”)。帮助将不胜感激。 (很长的问题,很抱歉,我试图将其格式化为尽可能好的格式。)

1 个答案:

答案 0 :(得分:0)

{1-2, 1-5, 1-3, 2-4}需要停止(返回false)的字符不仅仅是一个enter number of number of nodes in the graph5 enter option 1.create graph 2.display 3.exit 1 enter source and destination nodes 1 2 enter source and destination nodes 1 5 enter source and destination nodes 1 3 enter source and destination nodes 2 4 enter source and destination nodes 0 0 enter option 1.create graph 2.display 3.exit 2 the nodes adjacent to node 1 are= 2 5 3 the nodes adjacent to node 2 are= 1 4 the nodes adjacent to node 3 are= 1 the nodes adjacent to node 4 are= 2 the nodes adjacent to node 5 are= 1 enter option 1.create graph 2.display 3.exit3 。在最初的情况下,一旦它撞到了顶墙,它将看起来正确并看到一堵墙,然后向下看并看到一个find_path,它不是一堵墙,因此它开始进行新的搜索。您最终会在迷宫中的两个方块之间跳动。

WALL如果移动到的不是楼层,则需要立即返回false。如果它是墙,则不是解决方案的一部分,也不是解决方案的一部分。或者,检查是否有下划线字符(似乎只是'+')。