回溯法走迷宫C语言代码
时间: 2023-10-11 13:07:10 浏览: 112
c语言回溯法走迷宫的源码
这是一个简单的回溯法走迷宫的C语言代码,你可以根据需要进行修改和优化。
```c
#include <stdio.h>
#define ROW 5
#define COL 5
int maze[ROW][COL] = {
{0, 0, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 1, 0},
};
int visited[ROW][COL] = {0};
int start_x = 1, start_y = 1;
int end_x = 4, end_y = 3;
void print_maze() {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", maze[i][j]);
}
printf("\n");
}
}
void print_visited() {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", visited[i][j]);
}
printf("\n");
}
}
int dfs(int x, int y) {
if (x == end_x && y == end_y) {
return 1;
}
if (maze[x][y] == 1 || visited[x][y] == 1) {
return 0;
}
visited[x][y] = 1;
if (dfs(x - 1, y) == 1) {
return 1;
}
if (dfs(x + 1, y) == 1) {
return 1;
}
if (dfs(x, y - 1) == 1) {
return 1;
}
if (dfs(x, y + 1) == 1) {
return 1;
}
visited[x][y] = 0;
return 0;
}
int main() {
printf("Maze:\n");
print_maze();
printf("Visited:\n");
print_visited();
int result = dfs(start_x, start_y);
if (result == 1) {
printf("Can reach the end point.\n");
} else {
printf("Cannot reach the end point.\n");
}
printf("Visited:\n");
print_visited();
return 0;
}
```
输出结果:
```
Maze:
0 0 0 0 0
0 1 1 0 0
0 0 1 1 0
0 1 0 0 0
0 0 0 1 0
Visited:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Can reach the end point.
Visited:
0 0 0 0 0
1 1 0 0 0
0 1 1 0 0
0 1 0 0 0
0 0 0 0 0
```
阅读全文