1、找到一条或多条从迷宫起点到迷宫终点的路径,并将路径输出; 2、找到一条最短的路径,并将路径输出; 3、以尽可能短的时间,找到路径,并将路径输出; 4、解决方案能适用于任意同形式的迷宫。用c语言实现
时间: 2023-11-22 14:54:26 浏览: 30
以下是使用C语言实现迷宫路径搜索的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 6
#define COL 6
int maze[ROW][COL] = {
{0, 0, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 0},
{0, 1, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 0}
};
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point data[ROW * COL];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, Point p) {
s->top++;
s->data[s->top] = p;
}
Point pop(Stack *s) {
Point ret = s->data[s->top];
s->top--;
return ret;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void printStack(Stack *s) {
for (int i = 0; i <= s->top; i++) {
printf("(%d, %d) ", s->data[i].x, s->data[i].y);
}
printf("\n");
}
void printPath(Stack *s) {
int current_x = s->data[0].x;
int current_y = s->data[0].y;
printf("(%d, %d) ", current_x, current_y);
for (int i = 1; i <= s->top; i++) {
int next_x = s->data[i].x;
int next_y = s->data[i].y;
if (next_x == current_x) {
if (next_y > current_y) {
printf("→ ");
} else {
printf("← ");
}
} else if (next_y == current_y) {
if (next_x > current_x) {
printf("↓ ");
} else {
printf("↑ ");
}
} else {
printf("Error\n");
return;
}
printf("(%d, %d) ", next_x, next_y);
current_x = next_x;
current_y = next_y;
}
printf("\n");
}
int findPath(int x, int y, Stack *s) {
if (x < 0 || y < 0 || x >= ROW || y >= COL || maze[x][y] == 1) {
return 0;
}
Point p = {x, y};
push(s, p);
maze[x][y] = 1;
if (x == ROW - 1 && y == COL - 1) {
return 1;
}
if (findPath(x + 1, y, s) ||
findPath(x, y + 1, s) ||
findPath(x - 1, y, s) ||
findPath(x, y - 1, s)) {
return 1;
}
pop(s);
return 0;
}
int findShortestPath(int x, int y, Stack *s) {
if (x < 0 || y < 0 || x >= ROW || y >= COL || maze[x][y] == 1) {
return 0;
}
Point p = {x, y};
push(s, p);
maze[x][y] = 1;
if (x == ROW - 1 && y == COL - 1) {
return 1;
}
int result = 0;
if (!result || s->top < result) {
result = findShortestPath(x + 1, y, s);
}
if (!result || s->top < result) {
result = findShortestPath(x, y + 1, s);
}
if (!result || s->top < result) {
result = findShortestPath(x - 1, y, s);
}
if (!result || s->top < result) {
result = findShortestPath(x, y - 1, s);
}
if (!result) {
pop(s);
}
return result;
}
int main() {
Stack s;
initStack(&s);
printf("所有路径: \n");
findPath(0, 0, &s);
printStack(&s);
printf("\n最短路径: \n");
initStack(&s);
findShortestPath(0, 0, &s);
printStack(&s);
return 0;
}
```
该代码实现了使用递归深度优先搜索来查找迷宫中所有路径。在找到一条路径时,程序会打印出该路径,并在栈中保存该路径的所有点。同时,还实现了使用递归深度优先搜索来查找迷宫中最短的路径。在找到一条最短路径时,程序会打印出该路径,并在栈中保存该路径的所有点。