写一个c语言实现的迷宫代码
时间: 2023-02-24 21:37:27 浏览: 86
好的,这是一个简单的c语言实现的迷宫代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define ROW 10
#define COL 10
int maze[ROW][COL] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 1, 0, 1, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
typedef struct {
int x;
int y;
} Pos;
Pos stack[ROW * COL]; // 栈,用于记录路径
int top = -1;
void push(Pos pos) {
stack[++top] = pos;
}
void pop() {
top--;
}
int is_empty() {
return top == -1;
}
Pos get_top() {
return stack[top];
}
int is_valid_pos(int x, int y) {
if (x < 0 || x >= ROW || y < 0 || y >= COL) {
return 0;
}
if (maze[x][y] == 0) {
return 1;
}
return 0;
}
void print_path() {
for (int i = 0; i <= top; i++) {
printf("(%d, %d) ", stack[i].x, stack[i].y);
}
printf("\n");
}
int main() {
Pos start = {0, 1};
Pos end = {ROW - 2, COL - 2};
push(start);
while (!is_empty()) {
Pos cur = get_top();
int x = cur.x;
int y = cur.y;
if (x == end.x && y == end.y) {
print_path();
return 0;
}
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (is_valid_pos(nx, ny)) {
Pos
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)