单身的1暗恋上了一个女生,于是想给她告白,于是就在房间里用蛋糕堆了一个心的形状。
可是天公不作美,在这个房间的某个角落里藏着一只小老鼠,小老鼠虎视眈眈的看着这些蛋糕,想等1走之后去偷吃蛋糕。
一个房间可以看成n*n的方格。小老鼠可以往上、下、左、右四个方向走。问小老鼠吃到蛋糕最少需要多少步?
Input
本题有多组测试,每组测试第一行输入三个正整数n,x,y。n代表房间的长宽,(x,y)代表老鼠洞的位置(老鼠出现在老鼠洞这个点也算一步)。接下来n行是房间的布置, ’#’代表蛋糕,’.’代表空地。其中(x,y)一定满足位于房间的边上。
(7 ≤n ≤ 99,1 ≤ x,y ≤ n)
Output
对于每组测试数据输出一个整数,占一行。
Sample Input
11 1 8
...........
...........
...#...#...
..###.###..
.#########.
.#########.
..#######..
...#####...
....###....
.....#.....
...........
9 7 9
.........
.........
..##.##..
.#######.
.#######.
..#####..
...###...
....#....
.........
Sample Output
3
4
解题:使用广搜
#include<bits/stdc++.h>
#define maxn 105
using namespace std;
int vis[maxn][maxn];
char mp[maxn][maxn];
typedef struct node{
int x,y,cnt;
node(){}
node(int a,int b,int c):x(b),y(c),cnt(a){}
}nodepoint;
queue<node>q;
int n,x,y,cnt;
int add_up(int cnt,int x,int y){
nodepoint p1(cnt+1,x+1,y);
q.push(p1);
nodepoint p2(cnt+1,x-1,y);
q.push(p2);
nodepoint p3(cnt+1,x,y+1);
q.push(p3);
nodepoint p4(cnt+1,x,y-1);
q.push(p4);
}
void bfs(){
for (int i=0;i<n;i++)
fill(vis[i],vis[i]+maxn,0);
while (!q.empty()){
nodepoint p=q.front();
q.pop();
if(p.x >= 0 && p.x < n && p.y >= 0 && p.y < n &&vis[p.x][p.y] == 0){
cnt = p.cnt;
vis[p.x][p.y] = cnt;
if(mp[p.x][p.y] == '#'){
break;
}
else{
add_up(p.cnt,p.x,p.y);
}
}
}
}
int main(){
while (cin>>n>>x>>y){
cnt=0;
getchar();
while(!q.empty())
q.pop();
for (int i=0;i<n;i++)
gets(mp[i]);
nodepoint p(1,x-1,y-1);
q.push(p);
bfs();
printf("%d\n",cnt);
}
}