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

来源:互联网 发布:购房增值税的算法 编辑:程序博客网 时间:2024/06/06 18:24

深度搜素, 利用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;}


原创粉丝点击