http://poj.org/problem?id=3009
Simulates the movement of the curling, giving the minimum number of throws to reach the end point (1 if not reached).
The specific move rules are as follows:
Select one of four directions at a time to move forward in this direction until you hit block or out of bounds or arrive at the target location.
If you hit a block, the ice pot stops in the block's previous position and the block disappears, changing the direction of the curling (re-throwing).
If it is out of bounds, the moving path ends with a failure;
If you arrive at the target location, record the number of times the move path is thrown altogether.
The number of throws does not exceed 10 times for the success path.
If there is a successful path, the minimum number of throws is output, and the output-1 is not present.
The code below, due to the small amount of data, can be used DFS to get all the solution and then take the minimum value; Pay attention to reverting the modified block when backtracking:
1#include <cstdio>2#include <cstring>3 using namespacestd;4 5 Const intMax_n = A;6 7 intN, M;8 intG[max_n][max_n];9 intdx[]={0,0,1,-1}, dy[]={1, -1,0,0};Ten intSX, SY, GX, GY; One intMin_ans; A - - BOOLInsideintXinty) { the if(x<0|| X>=n | | y<0|| Y>=M)return false; - return true; - } - + voidDfsintXintYintCNT) { - if(CNT >Ten)return ; + for(intI=0; i<4; i++){ A intNX = x +Dx[i]; at intNY = y +Dy[i]; - if(!inside (x, y))Continue;//Out of bounds - if(G[nx][ny] = =1)Continue;//Block - Else{ - while(Inside (NX, NY) && g[nx][ny]! =1&& G[nx][ny]! =3){ -NX + =Dx[i]; inNY + = Dy[i];//go in this direction until block - } to if(!inside (NX, NY))Continue;//This direction is finally out of bounds + if(G[nx][ny] = =3){ -Min_ans = Cnt<min_ans?Cnt:min_ans; the Continue;//hit halfway in this direction * } $ Panax NotoginsengG[nx][ny] =0;//Block disappears -NX-=Dx[i]; theNY-= Dy[i];//arrive at the last valid position in this direction, the previous one of block + //printf ("%d%d\n", Dx[i], dy[i]); ADFS (NX, NY, cnt+1); theNX + =Dx[i]; +NY + =Dy[i]; -G[nx][ny] =1;//Restore, Backtracking $ } $ } - return ; - } the - intMain ()Wuyi { theFreopen ("3009.txt","R", stdin); - while(SCANF ("%d%d", &m, &n)! =EOF) { Wu if(m==0&& n==0) Break; - for(intI=0; i<n; i++){ About for(intj=0; j<m; J + +){ $scanf"%d", &g[i][j]); - if(G[i][j] = =2){ -SX =i; -SY =J; A}Else if(G[i][j] = =3){ +GX =i; theGY =J; - } $ } the } the theMin_ans = in;//any value greater than 10 theDFS (SX, SY,1);//throwing for the first time - if(Min_ans >Ten) Min_ans =-1; inprintf"%d\n", Min_ans); the } the return 0; About}
Pay attention to the framework of this kind of search and the basic concepts of backtracking method, such as constraint condition, Slipknot point, etc.
"POJ 3009 Curling2.0 Maze Quest DFS"