Http://poj.org/problem? Id = 3009
In fact, at the beginning, we wanted to use dir as a parameter and search based on the map condition, but it was processed with while in recursion. It was hard to process the backtracking of map from 0 to 1.
The code that hurts is tangled ..
Code:
# Include <cstdio>
# Include <cstring>
# Define min (A, B) A> B? B:
# Define Max 1E + 6
Int Tur [4] [2] = {0, 1, 0,-1, 1, 0,-1, 0 };
Int map [21] [21];
Int W, H, ANS, Sx, Sy, ex, ey;
Bool check (int x, int y ){
If (x <0 | x> = w | Y <0 | Y> = h) return false;
Return true;
}
Void DFS (int x, int y, int Dir, int count ){
Int Tx = x + Tur [dir] [0];
Int ty = Y + Tur [dir] [1];
If (! Check (TX, Ty) | count> 10)
Return;
If (Map [TX] [ty] = 1 ){
Map [TX] [ty] = 0;
For (INT I = 0; I <4; I ++ ){
If (Map [x + Tur [I] [0] [Y + Tur [I] [1] = 1 |! Check (x + Tur [I] [0], Y + Tur [I] [1]) continue;
DFS (x, y, I, Count + 1 );
}
Map [TX] [ty] = 1;
}
Else if (Map [TX] [ty] = 3 ){
Ans = min (ANS, count );
Return;
} Else {
DFS (TX, Ty, Dir, count );
}
}
Int main (){
Int I, J;
While (~ Scanf ("% d", & W, & H) & W + H ){
For (I = 0; I For (j = 0; j <W; j ++ ){
Scanf ("% d", & map [J] [I]);
If (Map [J] [I] = 2) SX = J, Sy = I;
Else if (Map [J] [I] = 3) EX = J, ey = I;
}
Ans = max;
For (I = 0; I <4; I ++ ){
If (Map [SX + Tur [I] [0] [SY + Tur [I] [1] = 1 |! Check (SX + Tur [I] [0], SY + Tur [I] [1]) continue;
DFS (sx, Sy, I, 1 );
}
If (ANS = max) printf ("-1 \ n ");
Else printf ("% d \ n", ANS );
}
Return 0 ;}