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

来源:互联网 发布:excel表格怎样筛选数据 编辑:程序博客网 时间:2024/05/15 13:18
给定一个大小为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;
}

0 0
原创粉丝点击