最简单的迷宫

#include <iostream>
#include <stack>
#include <queue>
using namespace std;
 
struct p
{
 int x, y, d;
};

int vis[100][100], dis[100][100];
int fx[100][100], fy[100][100];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};

int main()
{
 char g[100][100];
 queue <p> q;
 stack <p> s;
 int m, n, i, j;
 int sx, sy, ex, ey;
 int xx, yy;
 cin >> m >> n;
 while(!q.empty())
 {
  q.pop();
 }
 while(!s.empty())
 {
  s.pop();
 }
 for(i = 0; i < m; i++)
 {
  for(j = 0; j < n; j++)
  {
   cin >> g[i][j];
   vis[i][j] = 0;
  }
 }
 for(i = 0; i < m; i++)
 {
  for(j = 0; j < n; j++)
  {
   if(g[i][j] == 's')
   {
    sx = j;
    sy = i;
    }
    if(g[i][j] == 't')
    {
     ex = j;
     ey = i;
    }
  }
 }
 p temp, cur;
 temp.x = sx;
 temp.y = sy;
 temp.d = 0;
 q.push(temp);
 while(!q.empty())
 {
  cur = q.front();
  q.pop();
  for(i = 0; i < 4; i++)
  {
   yy = cur.y + dir[i][0];
   xx = cur.x + dir[i][1];
   if(g[yy][xx] != '#' && vis[yy][xx] == 0 && m > xx && xx >= 0 && n > yy && yy >= 0)
   {
    temp.x = xx;
    temp.y = yy;
    temp.d = cur.d + 1;
    fx[yy][xx] = cur.x;
    fy[yy][xx] = cur.y;
    dis[yy][xx] = cur.d + 1;
    q.push(temp);
   }
   vis[cur.y][cur.x] = 1;
  }
 }
 if(vis[ey][ex] == 0)
 {
  cout << "NO" << endl;
 }
 else
 {
  cout << "Yes" << endl;
  cout << dis[ey][ex] << endl;
 }
 temp.x = ex;
 temp.y = ey;
 yy = ey;
 xx = ex;
 s.push(temp);
 while ( g[yy][xx] != 's')
 {
  temp.y = fy[yy][xx];
  temp.x = fx[yy][xx];
//  cout << temp.y  << "  " << temp.x << endl;
  s.push(temp);
  yy = temp.y;
     xx = temp.x;
//  cout << temp.y  << "  " << temp.x << endl;
 }
 while(!s.empty())
 {
  temp = s.top();
  cout <<"("<< temp.x << "," << temp.y << ")" << endl;
  s.pop();
 }
 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值