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

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

 #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;
}

提康德罗加F
14 声望3 粉丝

fool