【数据结构】用栈实现迷宫

#include <iostream>
using namespace std;
#define N 10

#include <stack>

struct pos
{
     int _row;// 行
     int _col;// 列
};

bool cheakstep(pos a)
{
     if(a._col > -1||a._col < N-1||
         a._row > -1||a._row < N-1)
    {
          return true ;
    }
     return false ;
}

bool IsPath(int arr[][N],pos Nowloction,stack<pos>& s)
{

    pos tmp = Nowloction;
     //入栈标记  栈不为空
    s.push (Nowloction);
    arr[tmp._row][tmp._col] = 2;

     while(!s.empty ())
    {

          //shang
         pos Now = s.top ();

          if(Now._row == N-1)
         {
              return true ;
         }

         Now._row -=1;
          if(cheakstep(Now)==true && arr[Now._row][Now._col]==0)
         {
             s.push (Now);
             arr[Now._row ][Now._col ]=2;
              continue;
         }
          //you
         Now = s.top ();
         Now._col +=1;
          if(cheakstep(Now)==true && arr[Now._row][Now._col]==0)
         {
             s.push (Now);
             arr[Now._row ][Now._col ]=2;
              continue;
         }
         
          //xia
         Now = s.top ();
         Now._row +=1;
          if(cheakstep(Now)==true && arr[Now._row][Now._col]==0)
         {
             s.push (Now);
             arr[Now._row ][Now._col ]=2;
              continue;
         }

          //zuo
         Now = s.top ();
         Now._col -=1;
          if(cheakstep(Now)==true && arr[Now._row][Now._col]==0)
         {
             s.push (Now);
             arr[Now._row ][Now._col ]=2;
              continue;
         }

          else
         {
             Now = s.top ();
             arr[Now._row ][Now._col ] = 3;
             s.pop ();

         }
    }
    
     return false ;
}

int main()
{
     //定义一个二维数组存放迷宫 1表示墙0表示路
     //定义一个栈存放路径
     //定义一个入口地址
     int arr[N][N]={
    1,1,};
    pos entry = {2,0};
    stack<pos> path;



     bool ret = IsPath(arr,entry,path);

     if(ret == true )
    {
         cout<< "走出迷宫"<<endl;
    }
     else
         cout<< "没有走出迷宫"<<endl;


     for(int i=0;i<N;i++)
    {
          for(int j=0;j<N;j++)
         {
             cout<<arr[i][j];
         }
         cout<<endl;
    }
    cout<<endl;
     return 0;
}

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...