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
NO
YES
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
int n,m,t;
int start1,start2;
int finish1,finish2;
char ch[10][10];
int book[10][10];
int dir[4][2]={1,0,0,1,-1,0,0,-1};
int ans;
void dfs(int x,int y,int step)
{
if(ans==1)
return;
int tmp;
tmp=t-step-(fabs(x-finish1)+fabs(y-finish2));///奇偶剪枝
if(tmp<0||tmp%2!=0)
return;
if(ch[x][y]=='D'&&step==t)
{
ans=1;
return;
}
int tx,ty;
for(int i=0;i<4;i++)
{
tx=x+dir[i][0];
ty=y+dir[i][1];
if(tx<0||tx>n-1||ty<0||ty>m-1||ch[tx][ty]=='X'||book[tx][ty]==1)
continue;
book[tx][ty]=1;
dfs(tx,ty,step+1);
book[tx][ty]=0;
if(ans==1)
return;
}
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&t))
{
ans=0;
memset(book,0,sizeof(book));
if(n==0&&m==0&&t==0)
break;
for(int i=0;i<n;i++){
scanf("%s",ch[i]);
for(int j=0;j<m;j++){
if(ch[i][j]=='S')
{
start1=i;
start2=j;
}
if(ch[i][j]=='D')
{
finish1=i;
finish2=j;
}
}
}
book[start1][start2]=1;///一定要在标记开始地点位置坐标 已经走过,不然的话 后面会重复走。
dfs(start1,start2,0);
if(ans==1)
printf("YES\n");
else
printf("NO\n");
}
}