2014-12-13迷宫的最短路径

给定一个大小为N*M的迷宫,迷宫由通道和墙壁组成,每一步可以向邻接的上下左右的四格通道移动,请求出从起点到终点所需的最小步数。请注意,本题假定一定可以从起点移动到终点N,M<=100输入为第一行两个数,分别为N和M,然后接下来N行M列是迷宫,其中‘#’表示墙壁,‘.’表示通道,'S'表示起点,‘G’表示终点样例110 10#S######.#......#..#.#.##.##.#.#........##.##.####....#....#.#######.#....#......####.###.....#...G#输出:22


 

 #include <iostream>
#include <queue>
#include <string>
using namespace std;
int b1,b2,e1,e2,m,n;
int a[101][101]={0},flag[101][101]={0};
struct T{
 int x,y,n;
};
queue <T> Q;
bool check(int x,int y)
{
 if( !flag[x][y] && a[x][y] == 1)
  if(x >= 0 && x < n && y >= 0 && y < m )
   return true;
 return false;
}
int BFS()
{
 int i,ord[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
 T head,temp;
 head.x=b1;
 head.y=b2;
 head.n=0;
 Q.push(head);
 while(!Q.empty())
 {
  head=Q.front();     //逐层检测,每次从头部第一个检测,即最上层余下的第一个
  Q.pop();           //队列从头部(front)出队,将每一层的每一种情况遍历
  for(i=0;i<4;i++)
  {
   temp.x=head.x+ord[i][0];
   temp.y=head.y+ord[i][1];
   if(check(temp.x,temp.y))
   {
    temp.n=head.n+1;
    flag[temp.x][temp.y]=1;
    Q.push(temp);     //逐层入队
    if( temp.x == e1 && temp.y == e2 )
     return temp.n;
   }
  }
 }
 return 0;
}
int main()
{
 int i,j;
 string str;
 cin>>n>>m;
 for(i=0;i<n;i++)
 {
  cin>>str;
  for(j=0;j<m;j++)
  {
   if(str[j]=='#')   a[i][j]=0;
   else if(str[j]=='.') a[i][j]=1;
   else if(str[j]=='S') {b1=i;b2=j;a[i][j]=0;}
   else if(str[j]=='G') {e1=i;e2=j;a[i][j]=1;}
  }
 }
 cout<<BFS();
 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值