數據算法-使用棧實現迷宮

迷宮問題在給定迷宮以及出入點後求出一條可行的路徑,在此使用棧實現,如圖所示。
圖片描述ios

主要代碼以下:
頭文件爲:spa

#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文件爲:code

//#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;
}
相關文章
相關標籤/搜索