用C语言写一个迷宫问题
时间: 2023-12-29 12:59:35 浏览: 33
好的,下面是一个用C语言写的简单的迷宫问题的解法:
#include <stdio.h>
#define ROW 5
#define COL 5
int maze[ROW][COL] = {
{0, 1, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0}
};
int visited[ROW][COL];
int start[2] = {0, 0};
int end[2] = {4, 4};
int is_valid(int x, int y) {
if (x < 0 || x >= ROW || y < 0 || y >= COL) {
return 0;
}
if (maze[x][y] == 1 || visited[x][y] == 1) {
return 0;
}
return 1;
}
int dfs(int x, int y) {
if (x == end[0] && y == end[1]) {
return 1;
}
visited[x][y] = 1;
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int i = 0; i < 4; i++) {
int new_x = x + directions[i][0];
int new_y = y + directions[i][1];
if (is_valid(new_x, new_y)) {
if (dfs(new_x, new_y)) {
return 1;
}
}
}
return 0;
}
int main() {
int result = dfs(start[0], start[1]);
if (result) {
printf("可以找到出口!\n");
} else {
printf("无法找到出口!\n");
}
return 0;
}
希望对你有帮助!