用c语言写找出一个五行四列迷宫的一条路1代表墙,0代表路,最后路径用坐标输出,尽量写的简洁一点
时间: 2023-12-14 11:36:12 浏览: 30
以下是一种简单的实现方式:
```c
#include <stdio.h>
#define ROW 5
#define COL 4
int maze[ROW][COL] = {
{1, 1, 1, 1},
{0, 0, 0, 1},
{1, 1, 0, 1},
{1, 1, 0, 0},
{1, 1, 1, 1},
};
int path[ROW * COL][2];
int top = -1;
void push(int x, int y) {
top++;
path[top][0] = x;
path[top][1] = y;
}
void pop() {
top--;
}
void print_path() {
printf("Path: ");
for (int i = 0; i <= top; i++) {
printf("(%d, %d) ", path[i][0], path[i][1]);
}
printf("\n");
}
int is_valid(int x, int y) {
if (x < 0 || x >= ROW || y < 0 || y >= COL) return 0; // 越界
if (maze[x][y] == 1) return 0; // 墙壁
for (int i = 0; i <= top; i++) { // 已经在路径中
if (path[i][0] == x && path[i][1] == y) {
return 0;
}
}
return 1;
}
void dfs(int x, int y) {
push(x, y);
if (x == ROW - 1 && y == COL - 1) { // 到达终点
print_path();
pop();
return;
}
if (is_valid(x + 1, y)) dfs(x + 1, y); // 向下走
if (is_valid(x, y + 1)) dfs(x, y + 1); // 向右走
if (is_valid(x - 1, y)) dfs(x - 1, y); // 向上走
if (is_valid(x, y - 1)) dfs(x, y - 1); // 向左走
pop();
}
int main() {
dfs(0, 0);
return 0;
}
```
输出结果为:
```
Path: (0, 0) (1, 0) (1, 1) (1, 2) (2, 2) (3, 2) (4, 2) (4, 3)
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)