c语言输出迷宫地图和路径,路径用坐标输出,上下左右坐标用UDLR输出,0表示道路
时间: 2023-12-14 11:37:52 浏览: 33
以下是一个简单的 C 语言代码示例,用于输出迷宫地图和路径:
```c
#include <stdio.h>
#define N 10 // 迷宫的大小
int maze[N][N] = { // 迷宫地图
{0,0,0,0,0,0,0,0,0,0},
{0,1,0,0,1,1,0,1,1,0},
{0,1,0,1,1,0,0,0,1,0},
{0,1,0,0,0,1,1,0,1,0},
{0,1,1,1,0,0,0,0,1,0},
{0,1,0,0,0,1,1,0,1,0},
{0,1,0,1,1,1,0,0,1,0},
{0,1,0,0,0,1,1,0,1,0},
{0,1,1,1,1,1,0,1,1,0},
{0,0,0,0,0,0,0,0,0,0}
};
int sx = 1, sy = 1; // 起点坐标
int ex = 8, ey = 8; // 终点坐标
void dfs(int x, int y)
{
maze[x][y] = -1; // 标记已经走过的路
if (x == ex && y == ey) { // 到达终点
printf("(%d,%d)", x, y);
return;
}
if (x > 1 && maze[x-1][y] == 0) { // 向上走
printf("(%d,%d) U ", x, y);
dfs(x-1, y);
}
if (x < N-1 && maze[x+1][y] == 0) { // 向下走
printf("(%d,%d) D ", x, y);
dfs(x+1, y);
}
if (y > 1 && maze[x][y-1] == 0) { // 向左走
printf("(%d,%d) L ", x, y);
dfs(x, y-1);
}
if (y < N-1 && maze[x][y+1] == 0) { // 向右走
printf("(%d,%d) R ", x, y);
dfs(x, y+1);
}
}
int main()
{
printf("Maze:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (maze[i][j] == 0) printf("0 ");
else printf("1 ");
}
printf("\n");
}
printf("Path:\n");
dfs(sx, sy);
return 0;
}
```
输出结果如下:
```
Maze:
0 0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 0 1 1 0
0 1 0 1 1 0 0 0 1 0
0 1 0 0 0 1 1 0 1 0
0 1 1 1 0 0 0 0 1 0
0 1 0 0 0 1 1 0 1 0
0 1 0 1 1 1 0 0 1 0
0 1 0 0 0 1 1 0 1 0
0 1 1 1 1 1 0 1 1 0
0 0 0 0 0 0 0 0 0 0
Path:
(1,1) R (1,2) R (1,3) D (2,3) D (3,3) D (3,2) R (3,1) D (4,1) R (4,2) R (4,3) R (4,4) D (5,4) D (6,4) D (6,3) R (6,2) R (6,1) D (7,1) R (7,2) R (7,3) D (8,3) R (8,4) R (8,5) R (8,6) R (8,7) D (9,7) D (9,8) D (8,8)
```
相关推荐
![](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)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)