您的位置:首页 > 其它

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

2017-12-11 17:56 260 查看
深度搜素, 利用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: