《挑战程序设计比赛》 P35 题目:迷宫的最短路径 广度搜索

深度搜素, 利用STL中的 Queue


10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

#include <bits/stdc++.h>
using namespace std;

struct P{
      int x;
      int y;
      int dis;
      P(int x,int y ,int dis){
            this->x =x;
            this->y=y;
            this->dis=dis;
      }
};

int N,M;
char yard[100][100];

int dx[]={0,  0 ,  1, -1  };
int dy[]={1 , -1 , 0,  0  };
int sx,sy,gx,gy;


void  bfs(){

      queue<P> Q;
      Q.push( P(sx,sy,0) );

      while( !Q.empty() ) {
            P p=Q.front();  Q.pop();

            for(int i=0;i<4;i++){
                  int  newx = p.x + dx[i];
                  int  newy = p.y + dy[i];
                   if( newx == gx &&  newy == gy ) {
                              cout <<  p.dis + 1;
                              return;
                   }

                  if( newx>=0 && newx<N && newy>0 && newy<M && yard[newx][newy]=='.' )
                       {
                             Q.push( P( newx, newy, p.dis+1 ) );
                             yard[newx][newy] = '#';
                      }

            }

      }

}

int main()
{

      cin >> N >> M ;
      for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                  char t;   //这里调试了半个小时。  误输入了int
                  cin >>  t;
                  if( t=='S') { sx=i; sy=j;}
                  if( t=='G') { gx=i; gy=j;}
                  yard[i][j] = t;
            }
      }
      bfs();

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值