OpenJ Bailian3726-仙岛求药BFS
原题链接:http://bailian.openjudge.cn/practice/3726?lang=en_US
少年李逍遥的婶婶病了,王小虎介绍他去一趟仙灵岛,向仙女姐姐要仙丹救婶婶。叛逆但孝顺的李逍遥闯进了仙灵岛,克服了千险万难来到岛的中心,发现仙药摆在了迷阵的深处。迷阵由M×N个方格组成,有的方格内有可以瞬秒李逍遥的怪物,而有的方格内则是安全。现在李逍遥想尽快找到仙药,显然他应避开有怪物的方格,并经过最少的方格,而且那里会有神秘人物等待着他。现在要求你来帮助他实现这个目标。
下图 显示了一个迷阵的样例及李逍遥找到仙药的路线.
Input
输入有多组测试数据. 每组测试数据以两个非零整数 M 和 N 开始,两者均不大于20。M 表示迷阵行数, N 表示迷阵列数。接下来有 M 行, 每行包含N个字符,不同字符分别代表不同含义: 1) ‘@’:少年李逍遥所在的位置; 2) ‘.’:可以安全通行的方格; 3) ‘#’:有怪物的方格; 4) ‘*’:仙药所在位置。
当在一行中读入的是两个零时,表示输入结束。
Output
对于每组测试数据,分别输出一行,该行包含李逍遥找到仙药需要穿过的最少的方格数目(计数包括初始位置的方块)。如果他不可能找到仙药, 则输出 -1。
Simple Input
8 8
.@##…#
#…#.#
#.#.##…
…#.###.
#.#…#.
…###.#.
…#.…
.#…###
6 5
..#.
.#…
…##.
…
.#…
…@
9 6
.#…#.
.#.*.#
.####.
…#…
…#…
…#…
…#…
#.@.##
.#…#.
0 0
Sample Output
10
8
-1
代码如下:
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
struct node{
int x,y,step;
};
char mmap[21][21];
int book[21][21];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int m,n,sx,sy,ex,ey;
int num;
void bfs(int x,int y){
node s,now,next;
s.x=x;
s.y=y;
s.step=0;
book[x][y]=1;
queue<node>qu;
qu.push(s);
while(!qu.empty()){
now=qu.front();
//cout<<"("<<now.x<<","<<now.y<<"):"<<now.step<<endl;
qu.pop();
if(now.x==ex&&now.y==ey){
num=now.step;
return ;
}
for(int i=0;i<4;i++){
next.x=now.x+dx[i];
next.y=now.y+dy[i];
next.step=now.step;
if(book[next.x][next.y]==0&&next.x>=1&&next.x<=n&&next.y>=1&&next.y<=m&&mmap[next.x][next.y]!='#'){//注意mmap的判断条件
book[next.x][next.y]=1;
next.step+=1;
qu.push(next);
}
}
}
return ;
}
int main()
{
while(cin>>n>>m){
if(n==0&&m==0) break;
num=-1;//初始化!!
memset(mmap,0,sizeof(mmap));
memset(book,0,sizeof(book));
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mmap[i][j];
if(mmap[i][j]=='@'){
sx=i;sy=j;
}
if(mmap[i][j]=='*'){
ex=i;ey=j;
}
}
}
bfs(sx,sy);
cout<<num<<endl;
}
return 0;
}