c语言递归求解迷宫所有路径
时间: 2023-11-28 22:04:31 浏览: 81
下面是一个使用 C 语言递归算法求解迷宫所有路径的示例代码:
```c
#include <stdio.h>
#define ROW 5
#define COL 5
int maze[ROW][COL] = {
{0, 0, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0}
};
void printPath(int path[], int len) {
for (int i = 0; i < len; i++) {
printf("(%d,%d)->", path[i] / COL, path[i] % COL);
}
printf("\n");
}
void findPath(int row, int col, int path[], int len) {
if (row < 0 || row >= ROW || col < 0 || col >= COL) {
return;
}
if (maze[row][col] == 1) {
return;
}
if (row == ROW - 1 && col == COL - 1) {
printPath(path, len);
return;
}
maze[row][col] = 1;
path[len++] = row * COL + col;
findPath(row - 1, col, path, len);
findPath(row + 1, col, path, len);
findPath(row, col - 1, path, len);
findPath(row, col + 1, path, len);
maze[row][col] = 0;
}
int main() {
int path[ROW * COL];
findPath(0, 0, path, 0);
return 0;
}
```
代码中的 `maze` 数组表示迷宫地图,其中 0 表示可以通过的路,1 表示不可通过的障碍物。`findPath` 函数使用递归算法搜索迷宫所有路径,参数 `row` 和 `col` 表示当前位置,`path` 数组保存路径上的位置,`len` 表示路径长度。函数先对当前位置进行边界和障碍物检查,如果可以通过,则在 `maze` 数组中标记为已访问,并将当前位置加入到 `path` 数组中。然后递归搜索当前位置的上、下、左、右四个方向,直到搜索到终点或无法继续搜索。如果搜索到终点,则输出路径。最后,将 `maze` 数组恢复为未访问状态,以便搜索其他路径。
运行该程序,将输出所有从起点到终点的路径:
```
(0,0)->(1,0)->(2,0)->(2,1)->(2,2)->(3,2)->(4,2)->(4,3)->(4,4)->
(0,0)->(1,0)->(2,0)->(2,1)->(2,2)->(3,2)->(3,3)->(4,3)->(4,4)->
(0,0)->(1,0)->(2,0)->(2,1)->(2,2)->(3,2)->(3,3)->(3,4)->(4,4)->
(0,0)->(1,0)->(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,3)->(4,4)->
(0,0)->(1,0)->(1,1)->(2,1)->(2,2)->(3,2)->(3,3)->(4,3)->(4,4)->
(0,0)->(0,1)->(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,3)->(4,4)->
(0,0)->(0,1)->(1,1)->(2,1)->(2,2)->(3,2)->(3,3)->(4,3)->(4,4)->
(0,0)->(0,1)->(1,1)->(2,1)->(2,2)->(3,2)->(3,3)->(3,4)->(4,4)->
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(4,3)->(4,4)->
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,3)->(4,3)->(4,4)->
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,3)->(3,4)->(4,4)->
(0,0)->(0,1)->(0,2)->(1,2)->(2,2)->(3,2)->(4,2)->(4,3)->(4,4)->
(0,0)->(0,1)->(0,2)->(1,2)->(2,2)->(3,2)->(3,3)->(4,3)->(4,4)->
(0,0)->(0,1)->(0,2)->(1,2)->(2,2)->(3,2)->(3,3)->(3,4)->(4,4)->
(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(2,3)->(3,3)->(4,3)->(4,4)->
(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(2,3)->(3,3)->(3,4)->(4,4)->
```
阅读全文