id=3009 "> Link: poj 3009
Test Instructions : On an ice grid panel, there are gaps (barrier-free), and barrier blocks. There is a small stone, given its starting point and end point. Minimum number of steps from start to end
rule : Small stones can not move in the barrier area, once the movement from a certain direction, will not change direction, will not stop. This is a step, unless you encounter an obstacle or arrive at the end of the stop. If you encounter obstacles. The small stone will stop next to the obstacle, and an obstacle will disappear .
input : 1 stands for obstructions (unreachable), 0 for blank area, 2 for starting point. 3 represents the end point
Output : If the small stone can reach the end point, and the number of steps is up to 10 steps, output the minimum number of steps, otherwise output-1.
idea :dfs+ backtracking
To determine whether a small stone is a movement or a delicate state, if it is delicate, next to the obstacle zone. is not allowed to go. And when starting a small stone movement, to the next stop for the first step, the period direction has not changed. Only after the ability to change the direction of movement, so DFS to determine the movement of small stones and direction.
Pruning: This can be used as a pruning condition because the number of steps cannot exceed 10
#include <stdio.h>int m,n,a[21][21],min;int x[4]={-1,1,0,0},y[4]={0,0,-1,1};void dfs (int i,int j,int Step,int Dir,int sta,int flag) {//step Indicates the current number of steps, dir motion direction. STA Motion State, flag whether to remove the barrier int k,r,c; if (step>10)//pruning, the number of steps can not exceed ten return; if (a[i][j]==3) {//reach the end point, if the number of steps is smaller than the minimum step, update the minimum steps if (step<min) min=step; return; } if (flag) {//Flag 1 o'clock, an obstacle block that eliminates the collision of small Stones r=i+x[dir]; C=j+y[dir]; a[r][c]=0; } if (!sta) {//Compact for (k=0;k<4;k++) {r=i+x[k]; C=J+Y[K]; if (r>=1&&r<=n&&c>=1&&c<=m&&a[r][c]!=1)//Inferred Boundary Dfs (r,c,step+1 , k,1,0); }} else{//Movement direction unchanged R=i+x[dir]; C=j+y[dir]; if (r>=1&&r<=n&&c>=1&&c<=m) {//Inferred boundary if (a[r][c]!=1) DFS (r,c , step,dir,1,0); ElSE//when encountering obstructions. Stop moving. The status STA becomes 0, and the next step is to remove the barrier. becomes 1 dfs (i,j,step,dir,0,1); } else//If the next step exceeds the boundary, you cannot continue the motion return; } if (flag) {R=i+x[dir]; C=j+y[dir]; A[r][c]=1; } return; int main () {int i,j,r,c; while (scanf ("%d%d", &m,&n)!=eof) {if (m==0&&n==0) break; for (i=1;i<=n;i++) for (j=1;j<=m;j++) {scanf ("%d", &a[i][j]); if (a[i][j]==2) {//Find starting point r=i; C=j; }} min=11; Since the minimum number of steps cannot exceed 10, it can be initialized to DFS (r,c,0,0,0,0); if (min==11) min=-1; printf ("%d\n", min); } return 0;}
POJ 3009 Curling 2.0 (DFS)