写一个c语言程序 输入一个5乘5的迷宫 1为可通行的地方0为障碍求迷宫的最短路径
时间: 2023-11-27 18:49:08 浏览: 77
以下是一个使用BFS算法求解迷宫最短路径的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROWS 5
#define COLS 5
typedef struct {
int x;
int y;
} Point;
Point queue[ROWS*COLS];
int front = 0, rear = 0;
void enqueue(Point p) {
queue[rear++] = p;
}
Point dequeue() {
return queue[front++];
}
int is_empty() {
return front == rear;
}
int is_valid(int x, int y, int maze[ROWS][COLS], int visited[ROWS][COLS]) {
if (x < 0 || x >= ROWS || y < 0 || y >= COLS) {
return 0;
}
if (maze[x][y] == 0 || visited[x][y] == 1) {
return 0;
}
return 1;
}
void print_path(Point path[], int len) {
int i;
for (i = 0; i < len; i++) {
printf("(%d,%d)", path[i].x, path[i].y);
if (i != len-1) {
printf("->");
}
}
printf("\n");
}
void bfs(int maze[ROWS][COLS], int visited[ROWS][COLS], Point start, Point end) {
int i, j;
Point path[ROWS*COLS];
int path_len = 0;
int found = 0;
Point directions[] = {{-1,0}, {0,1}, {1,0}, {0,-1}};
visited[start.x][start.y] = 1;
enqueue(start);
while (!is_empty()) {
Point p = dequeue();
path[path_len++] = p;
if (p.x == end.x && p.y == end.y) {
found = 1;
break;
}
for (i = 0; i < 4; i++) {
int new_x = p.x + directions[i].x;
int new_y = p.y + directions[i].y;
if (is_valid(new_x, new_y, maze, visited)) {
visited[new_x][new_y] = 1;
Point new_p = {new_x, new_y};
enqueue(new_p);
}
}
}
if (found) {
printf("The shortest path is: ");
print_path(path, path_len);
} else {
printf("No path found.\n");
}
}
int main() {
int maze[ROWS][COLS] = {
{1, 1, 0, 1, 1},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 1},
{0, 0, 0, 1, 0},
{1, 1, 1, 1, 1}
};
int visited[ROWS][COLS] = {0};
Point start = {0, 0};
Point end = {ROWS-1, COLS-1};
bfs(maze, visited, start, end);
return 0;
}
```
这个程序将一个5x5的迷宫存储为一个二维数组,其中1表示可通行的地方,0表示障碍。程序使用BFS算法在迷宫中搜索最短路径,并输出路径上的点坐标。
阅读全文