C语言走迷宫算法:使用广度优先搜索求解
好的,以下是一个基本的走迷宫的C语言代码示例:
#include <stdio.h>
#include <stdlib.h>
#define ROW 5
#define COL 5
int maze[ROW][COL] = {
{0,0,0,0,0},
{1,1,0,1,0},
{0,0,0,1,0},
{0,1,1,1,0},
{0,0,0,0,0}
};
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point point;
int step;
} Step;
int is_valid(int x, int y) {
return x >= 0 && x < ROW && y >= 0 && y < COL && maze[x][y] == 0;
}
void print_path(Step *path, int len) {
printf('Path found: ');
for (int i = 0; i < len; i++) {
printf('(%d,%d)', path[i].point.x, path[i].point.y);
if (i != len - 1) {
printf(' -> ');
}
}
printf('\n');
}
void solve_maze(Point start, Point end) {
int visited[ROW][COL] = {0};
Step queue[ROW * COL];
int front = 0, rear = 0;
queue[rear++] = (Step){start, 0};
visited[start.x][start.y] = 1;
while (front != rear) {
Step current = queue[front++];
if (current.point.x == end.x && current.point.y == end.y) {
Step path[ROW * COL];
int len = 0;
while (current.step != 0) {
path[len++] = current;
current = queue[current.step];
}
path[len++] = (Step){start, 0};
print_path(path, len);
return;
}
Point directions[4] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
for (int i = 0; i < 4; i++) {
Point next_pos = {current.point.x + directions[i].x, current.point.y + directions[i].y};
if (!is_valid(next_pos.x, next_pos.y) || visited[next_pos.x][next_pos.y]) {
continue;
}
queue[rear++] = (Step){next_pos, front - 1};
visited[next_pos.x][next_pos.y] = 1;
}
}
printf('No path found.\n');
}
int main() {
Point start = {0, 0};
Point end = {4, 4};
solve_maze(start, end);
return 0;
}
这个代码使用了广度优先搜索算法来找到迷宫中的路径。它首先将起点加入一个队列中,然后不断从队列中取出位置,并将它的相邻位置加入队列中。如果队列中的位置是终点,那么就返回路径。如果队列为空,那么就说明没有找到路径。
原文地址: https://www.cveoy.top/t/topic/jsEp 著作权归作者所有。请勿转载和采集!