Tempter of the Bone

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.

Input

The input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:

'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.

Output

For each test case, print in one line "YES" if the doggie can survive, or "NO" otherwise.

Sample Input

4 4 5

S.X.

..X.

..XD

....

3 4 5

S.X.

..X.

...D

0 0 0

Sample Output

NO

YES

 

题意描述:

判断小狗能否刚好在t时刻走到门口。

解题思路:

定义一个flag初始为0,利用深搜找到门,且时间为t时令flag为1,跳出函数;因深搜为递归函数,只是跳出了这一层函数,在函数前判断若flag为1,跳出。即可跳出所有。

 

#include<stdio.h>
#include<string.h>
#include<math.h>
int min,n,m,p,q,t,f,a[10][10],book[10][10];
void dfs(int x,int y,int step)
{
	int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
	int tx,ty,k;
	if(f==1)
		return;
	if(x==p&&y==q)
	{
		if(step==t)
			f=1;
		return ;
	}
	
	for(k=0;k<=3;k++)
	{
		tx=x+next[k][0];
		ty=y+next[k][1];
		if(tx<0||tx>n-1||ty<0||ty>m-1)
			continue;
		if(a[tx][ty]==0&&book[tx][ty]==0)
		{
			book[tx][ty]=1;
			dfs(tx,ty,step+1);
			book[tx][ty]=0;
		}	
	}
	return ;
}
int main()
{
	char str[10][10];
	int i,j,x,y,wall;
	while(scanf("%d%d%d",&n,&m,&t))
	{
		if(n==0&&m==0&&t==0)
			break;
		f=0;
		memset(a,0,sizeof(a));
		memset(book,0,sizeof(book));
		for(i=0;i<n;i++)
			scanf("%s",str[i]);
		for(i=0;i<n;i++)
			for(j=0;j<m;j++)
			{
				
				if(str[i][j]=='S')
				{
					x=i;
					y=j;
				}
				if(str[i][j]=='D')
				{
					p=i;
					q=j;
				}
				if(str[i][j]=='X')
					a[i][j]=1;		
			}
		book[x][y]=1;
		dfs(x,y,0);
		if(f==1)
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}