表白记 HRBUST - 1979
Problem Description
单身的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
solution
这道题是标准的广搜题,值得注意的是给出的老鼠方位在数组下标里需要进行减一操作;
code
#include<bits/stdc++.h>
using namespace std;
#define maxn 100
char mp[maxn][maxn];
int mp1[maxn][maxn];
typedef struct node{
int x,y,cnt;
node(int a,int b,int c){
cnt = a;
x = b;
y = c;
}
}creatnode;
queue<node> q;
int n,x,y,cnt = 0;
void add(int cnt,int x,int y){
creatnode p1(cnt + 1,x + 1,y);
q.push(p1);
creatnode p2(cnt + 1,x - 1,y);
q.push(p2);
creatnode p3(cnt + 1,x,y + 1);
q.push(p3);
creatnode p4(cnt + 1,x,y - 1);
q.push(p4);
}
void bfs(int x, int y){
for(int i = 0;i < n; i++)
fill(mp1[i],mp1[i] + maxn,0);
while(!q.empty()){
creatnode p = q.front();
q.pop();
if(p.x >= 0 && p.x < n && p.y >= 0 && p.y < n && mp1[p.x][p.y] == 0){
cnt = p.cnt;
mp1[p.x][p.y] = cnt;
if(mp[p.x][p.y] == '#'){
break;
}
else{
add(p.cnt,p.x,p.y);
}
}
}
}
int main()
{
while(cin >> n >> x >> y){
getchar();
while(!q.empty()) q.pop();
for(int i = 0;i < n; i++){
gets(mp[i]);
}
creatnode p(1,x - 1,y - 1);
q.push(p);
bfs(x,y);
cout << cnt << endl;
}
return 0;
}