【C++】迷宫的简单实现

写一个简单的迷宫

迷宫首先要有地图,我们的地图用一个二维数组表示


这个地图很简单,当为1时表示可以走通,当为0时表示走不通

代码实现思路:

1.送一个能走的起始点

2.创建一个栈,每走一步,把走的位置压入栈中

3.当四个方向都走不通时,出栈一次,返回上一个位置,并把不通的路标记为4,走过的路标记为2.

4.当走出数组且不是起始位置,则该迷宫可走通。

代码:

(1)迷宫中走的方式

#include<iostream>
#include<assert.h>
#include<stack>
using namespace std;
#define ROW 10
#defi
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
很高兴为您回答这个问题!以下是一个简单迷宫求解程序: ```c #include <stdio.h> // 定义迷宫大小和路径 #define ROW_SIZE 10 #define COL_SIZE 10 int maze[ROW_SIZE][COL_SIZE] = { {1,1,1,1,1,1,1,1,1,1}, {0,0,1,0,0,0,1,0,1,1}, {1,0,1,0,1,0,1,0,1,1}, {1,0,1,0,1,0,0,0,0,1}, {1,0,1,1,1,1,1,1,0,1}, {1,0,1,0,0,0,0,0,0,1}, {1,0,1,0,1,1,1,1,0,1}, {1,0,0,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1}, {0,0,0,0,0,0,0,0,0,1} }; int path[ROW_SIZE][COL_SIZE]; // 定义方向 #define EAST 0 #define NORTH 1 #define WEST 2 #define SOUTH 3 // 定义堆栈 #define MAX_STACK_SIZE 100 int stack[MAX_STACK_SIZE]; int top = -1; void push(int item) { if (top >= MAX_STACK_SIZE - 1) { printf("stack overflow\n"); return; } stack[++top] = item; } int pop() { if (top < 0) { printf("stack underflow\n"); return -1; } return stack[top--]; } int is_empty() { return top < 0; } int get_direction(int r, int c, int direction) { switch (direction) { case EAST: return maze[r][c + 1]; case NORTH: return maze[r - 1][c]; case WEST: return maze[r][c - 1]; case SOUTH: return maze[r + 1][c]; } } void print_path() { printf("Path:\n"); for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { printf("%d ", path[i][j]); } printf("\n"); } } void solve_maze(int r, int c, int direction) { push(direction); while (!is_empty()) { direction = pop(); path[r][c] = 1; if (r == ROW_SIZE - 1 && c == COL_SIZE - 1) { print_path(); return; } for (int i = direction + 1; i < direction + 5; i++) { int new_direction = i % 4; if (get_direction(r, c, new_direction) == 0) { switch (new_direction) { case EAST: c++; break; case NORTH: r--; break; case WEST: c--; break; case SOUTH: r++; break; } push(new_direction); break; } } } printf("No solution found\n"); } int main() { solve_maze(0, 0, EAST); return 0; } ``` 该程序使用堆栈和回溯来解决迷宫问题。迷宫的大小由 `ROW_SIZE` 和 `COL_SIZE` 定义,路径由 `maze` 数组表示。程序搜索所有可能的路径,打印出正确路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值