数据算法-使用栈实现迷宫

本文介绍了一种使用栈实现的迷宫寻路算法,通过定义点类和方向属性,递归地寻找从起点到终点的路径。代码示例展示了如何在给定的迷宫环境中找到一条可行的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

迷宫问题在给定迷宫以及出入点后求出一条可行的路径,在此使用栈实现,如图所示。
图片描述

主要代码如下:
头文件为:

 #ifndef MAZE_H_
    #define MAZE_H_
    #include<iostream>
    #include <string>
    #include <stack>

class point 
{
public :
    int x;
    int y;
    int dir;//这个dir不同决定了这个数据也是不同的,它的作用就是用来只是当前符合要求的地方的下一个current_point的值!current_point是不能压入栈的。
    point(int x_, int y_, int dir_ = 1);
    bool operator ==(const point& p)const;
};

#endif

cpp文件为:

//#include "maze.h"
using namespace std;
bool visited[11][11];
bool point::operator==(const point&p)const 
{
    return p.x == x&&p.y == y;
}
point::point(int a, int b, int c) :x(a), y(b), dir(c) {}
bool pass(int maze[][10], point p) 
{
    return !visited[p.x][p.y] && !maze[p.x][p.y];
}
point next_point(point p,int dir) 
{
    if (dir == 1)return point(p.x, p.y + 1);
    if (dir == 2)return point(p.x, p.y - 1);
    if (dir == 3)return point(p.x - 1, p.y);
    if (dir == 4)return point(p.x + 1, p.y);

}
std::stack<point> mazesolution(int maze[][10], point start, point end)
{
    stack<point> path;
    point current_point = start;
    do
    {
        if (pass(maze, current_point)) 
        {
            visited[current_point.x][current_point.y] = true;//标记已经走过的路径
            path.push(current_point);
            if (current_point == end) return path;
            current_point = next_point(current_point, 1);
        }
        else 
        {
            point pt = path.top();//准备修改方向
            path.pop();
            while (pt.dir == 4 && !path.empty()) 
            {
                pt = path.top();
                path.pop();
            }
            if (pt.dir < 4) 
            {
                pt.dir++;//对栈中符合要求的点修改dir,查看修改反向后指向的那个current数据是否是满足条件的,有个问题就是说current仅仅是作为判断的,不要压入栈!栈中只要有满足条件的点。
                path.push(pt);
                current_point = next_point(pt, pt.dir);
            }
        }
    } while (!path.empty());
    return path;
}
int main() {
 int maze[][10] = { 
{ 1,1,1,1,1,1,1,1,1,1 },
{ 1,0,0,1,0,0,0,1,0,1 },
{ 1,0,0,1,0,0,0,1,0,1 },
{ 1,0,0,0,0,1,1,0,0,1 },
{ 1,0,1,1,1,0,0,0,0,1 },
{1,0,0,0,1,0,0,0,0,1},
{ 1,0,1,0,0,0,1,0,0,1 },
{ 1,0,1,1,1,0,1,1,0,1 },
{ 1,1,0,0,0,0,0,0,0,1 },
{ 1,1,1,1,1,1,1,1,1,1 } };
point start(1, 1), end(8, 8);
   stack<point> path = mazesolution(maze, start, end);
       while (path.size()) {
                printf("(%d,%d) ", path.top().x, path.top().y);
                 path.pop();
        
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值