迷宫问题(栈的应用,二维数组表示迷宫)

#include <iostream>
#include <stack>
#define N 25
using namespace std;

struct Node{
int x;int y;
};
Node Move[8];
int Puzzle[N][N];
int row,column;
void Init();
void FindPath(Node destination);
void main()
{
 Init();
 Node t;
 t.x=row-2;t.y=column-2;
 FindPath(t);
 ::system("pause");
}
void Init()
{
 Node temp;temp.x=-1;temp.y=-1;
 Move[0]=temp;
 temp.x=0;temp.y=-1;Move[1]=temp;
 temp.x=1;temp.y=-1;Move[2]=temp;
 temp.x=1;temp.y=0;Move[3]=temp;
 temp.x=1;temp.y=1;Move[4]=temp;
 temp.x=0;temp.y=1;Move[5]=temp;
 temp.x=-1;temp.y=1;Move[6]=temp;
 temp.x=-1;temp.y=0;Move[7]=temp;
 cout<<"输入迷宫的行数、列数:\n";
 cin>>row>>column;
 for(int i=0;i<row;++i)
  for(int j=0;j<column;++j)
  {
   cout<<"请输入Puzzle["<<i<<"]["<<j<<"]的元素值:\n";
   cin>>Puzzle[i][j];

  }
 cout<<"初始化成功!\n";
}
void show(stack<Node> s)
{
 if(s.empty())return;
 Node temp=s.top();
 s.pop();
 show(s);
 cout<<" ("<<temp.x<<","<<temp.y<<") ";
}
void FindPath(Node destination)
{
 stack<Node> path;
 Node temp;temp.x=1;temp.y=1;
 path.push(temp);
 bool flag=false;
 while(!path.empty()&&!flag)
 {
  temp=path.top();
  int i=-1;
  while(i<8&&!flag)
  {
   for(i=0;i!=8;++i)
   {
    if(Puzzle[temp.x+Move[i].x][temp.y+Move[i].y]==0)
    {
     Puzzle[temp.x+Move[i].x][temp.y+Move[i].y]=1;
     temp.x=temp.x+Move[i].x;
     temp.y=temp.y+Move[i].y;
     path.push(temp);
     if(temp.x==destination.x&&temp.y==destination.y)
      flag=true;
     break;
    }
   }
  }
  if(!flag)
  {
   path.pop();
  }
   
 }
 if(flag)
 {
  show(path);
 }
 else
  cout<<"没有路径到达终点!\n";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值