用c语言写求迷宫最短路径长度
时间: 2024-01-10 08:04:46 浏览: 87
要用C语言求解迷宫最短路径长度,可以使用广度优先搜索算法。
首先,需要定义一个二维数组来表示迷宫,例如:
```c
int maze[5][5] = {
{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}
};
```
其中,0表示可以通行的空格,1表示墙或障碍物。
接下来,定义一个队列来存储每个可达的格子。对于每个可达的格子,存储其所在行列及到起点的步数。
```c
typedef struct {
int row, col, steps;
} Point;
Point queue[25];
int front = 0, rear = 0;
```
然后,从起点开始,将其加入队列,并将起点标记为已访问。
```c
Point start = {0, 0, 0};
queue[rear++] = start;
maze[0][0] = 1;
```
接着,使用循环遍历队列中的每个格子,查找其四周可达的格子,并将其加入队列。
```c
while (front < rear) {
Point current = queue[front++];
if (current.row == 4 && current.col == 4) {
printf("Shortest path length is %d\n", current.steps);
break;
}
if (current.row > 0 && maze[current.row-1][current.col] == 0) {
Point next = {current.row-1, current.col, current.steps+1};
queue[rear++] = next;
maze[current.row-1][current.col] = 1;
}
if (current.row < 4 && maze[current.row+1][current.col] == 0) {
Point next = {current.row+1, current.col, current.steps+1};
queue[rear++] = next;
maze[current.row+1][current.col] = 1;
}
if (current.col > 0 && maze[current.row][current.col-1] == 0) {
Point next = {current.row, current.col-1, current.steps+1};
queue[rear++] = next;
maze[current.row][current.col-1] = 1;
}
if (current.col < 4 && maze[current.row][current.col+1] == 0) {
Point next = {current.row, current.col+1, current.steps+1};
queue[rear++] = next;
maze[current.row][current.col+1] = 1;
}
}
```
最后,如果队列为空仍未找到终点,则说明不存在通往终点的路径。
完整代码如下:
```c
#include <stdio.h>
typedef struct {
int row, col, steps;
} Point;
Point queue[25];
int front = 0, rear = 0;
int maze[5][5] = {
{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 main() {
Point start = {0, 0, 0};
queue[rear++] = start;
maze[0][0] = 1;
while (front < rear) {
Point current = queue[front++];
if (current.row == 4 && current.col == 4) {
printf("Shortest path length is %d\n", current.steps);
break;
}
if (current.row > 0 && maze[current.row-1][current.col] == 0) {
Point next = {current.row-1, current.col, current.steps+1};
queue[rear++] = next;
maze[current.row-1][current.col] = 1;
}
if (current.row < 4 && maze[current.row+1][current.col] == 0) {
Point next = {current.row+1, current.col, current.steps+1};
queue[rear++] = next;
maze[current.row+1][current.col] = 1;
}
if (current.col > 0 && maze[current.row][current.col-1] == 0) {
Point next = {current.row, current.col-1, current.steps+1};
queue[rear++] = next;
maze[current.row][current.col-1] = 1;
}
if (current.col < 4 && maze[current.row][current.col+1] == 0) {
Point next = {current.row, current.col+1, current.steps+1};
queue[rear++] = next;
maze[current.row][current.col+1] = 1;
}
}
if (front >= rear) {
printf("No path found\n");
}
return 0;
}
```
阅读全文