Description April 16, after a strong earthquake in Kumamoto, Japan, a pig farm collapsed in a badly-hit ASO city, and fortunately, many pigs in the pigsty were still strong enough to survive. 15 local firefighters took a day to rescue the besieged "pigs strong". However, compared with the Chinese Wenchuan "pig-strong" who survived 36 days in the ruins by eating charcoal to drink rainwater, Xiongben's pigs were less fortunate because they eventually failed to escape the fate of being sent to the slaughterhouse. We assume that "pig is strong" trapped in a n*m ruins, where "@" means "pig strong" position, "." Indicates the vacant space which can be passed directly, "#" means that the obstruction cannot be demolished, "*" means that the obstruction can be demolished, so how many obstacles must the firemen demolish at least to rescue the "pig strong" from the ruins to the slaughterhouse. (When a "pig is strong" moves to the edge of the ruin through open space or demolished obstructions, as if it were rescued from the ruins) Input Multiple sets of data, the first line has an integer t, indicating that there is a T group of data. (t<=100) The first row of each group of data has two integers n and M. (1<=n,m<=100) then N rows with a string of length M for each row. Output
An integer, for the minimum number of demolished obstructions, if not escape from the ruins, output-1. Sample Input
3
3 3
# # #
#@*
* *
3 4
# #
#@.*
**.*
3 3
. #
#@#
.#.
Sample Output
1
0
-1
HINT
Bare BFS Template problem
#include <bits/stdc++.h> using namespace std;
const int MAXN = 105;
const int Dir[4][2] = {{-1, 0}, {1, 0}, {0,-1}, {0, 1}};
Char MAT[MAXN][MAXN];
BOOL FLAG[MAXN][MAXN];
int n, m;
struct node{int x, y;
int step;
BOOL operator < (const node & P) const{return step > P.step;
}
};
int BFS (int x, int y) {priority_queue<node> que;
Node p;
p.x = x;
P.y = y;
P.step = 0;
Que.push (P);
while (!que.empty ()) {p = que.top ();
Que.pop ();
x = p.x;
y = p.y;
int step = P.step;
if (x==0 | | y==0 | | x==n-1 | | y==m-1) return step;
Node pp;
for (int i=0; i<4; ++i) {pp.x = x+dir[i][0];
PP.Y = y+dir[i][1];
Pp.step = 0; if (pp.x>=0 && pp.x<n && pp.y>=0 && pp.y<m) {if (mat[pp.x][pp.y] = = ' *
') Pp.step = step+1; else if (mat[pP.X][PP.Y] = = '. ')
Pp.step = step+0;
else Pp.step =-1;
if (pp.step>=0 && flag[pp.x][pp.y]==false) {flag[pp.x][pp.y] = true;
Que.push (PP);
}}}} return-1;
} int main () {#ifdef LOCAL freopen ("Input.txt", "R", stdin);
Freopen ("Output.txt", "w", stdout);
#endif int T;
scanf ("%d", &t);
while (t--) {scanf ("%d%d", &n, &m);
for (int i=0; i<n; ++i) scanf ("%s", mat+i);
int TA, TB;
Memset (flag, false, sizeof (flag));
for (int i=0, i<n; ++i) for (int j=0; j<m; ++j) {if (mat[i][j] = = ' @ ') {
Ta = i;
TB = j;
}} FLAG[TA][TB] = true;
int ans = BFS (TA, TB);
printf ("%d\n", ans);
} return 0; }