The doggie found a bone in an ancient maze, which fascinated him a lot. However, when he picked it up, the maze began to shake, and the doggie could feel the ground sinking. He realized that the
bone was a trap, and he tried desperately to get out of this maze.
The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.
The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.
'X': a block of wall, which the doggie cannot enter;
'S': the start point of the doggie;
'D': the Door; or
'.': an empty block.
The input is terminated with three 0's. This test case is not to be processed.
4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0
Sample Output
NO
YES
奇偶剪枝加深度搜索,该题是剪枝应用的经典题目,能ac这一题,说明已经理解了奇偶剪枝。奇偶剪枝本身不难理解,如果画出一个01矩阵表,会发现从0到0无论你如何走都是需要偶数步,而从0到1无论如何走都需要偶数步,一次类推,在矩阵上的一点到另一点,无论怎么走,所需要的步数奇偶性是相等的。也就是说当点的步数加上当前点到终点的最少步数和起点到终点的最少步数同奇同偶。
代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
char s[10][10];
int b[10][10];
int m,n,min,t,t0,x,y,x2,y2;
int a[4][2]={0,1,1,0,-1,0,0,-1};
void fun(int zx,int zy,int step)
{
int nx,ny;
if(min!=-1)
return ;
if(s[zx][zy]=='D'&&step==t)
{
min=step;
return ;
}
int z,i;
z=abs(zx-x2)+abs(zy-y2);
if(z+step>t)
return ;
if((t-step-z)&1||(t-step-z)<0)
return ;
for(i=0;i<4;i++)
{
nx=zx+a[i][0];
ny=zy+a[i][1];
if(nx<0||ny<0||nx>=m||ny>=n)
continue;
if(b[nx][ny]==0&&s[nx][ny]!='X')
{
b[nx][ny]=1;
fun(nx,ny,step+1);
b[nx][ny]=0;
}
}
return ;
}
int main()
{
int i,j,k;
while(scanf("%d %d %d",&m,&n,&t),m+n+t!=0)
{
k=0;
memset(s,0,sizeof(s));
memset(b,0,sizeof(b));
for(i=0;i<m;i++)
{
scanf("%s",s[i]);
for(j=0;j<n;j++)
{
if(s[i][j]=='S')
x=i,y=j;
if(s[i][j]=='D')
x2=i,y2=j;
if(s[i][j]=='X')
k++;
}
}
t0=abs(x-x2)+abs(y-y2);
if(t+k>m*n)
{
printf("NO\n");
continue;
}
b[x][y]=1;
min=-1;
fun(x,y,0);
if(min==t)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}