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
题目链接:
题意描述:
从S出发终点是D,其中“X”是墙,“.”是路,需要在刚好t时刻到达终点,还有不能走重复的路
解体思路:
这是一个神搜的题,首先把模板敲上,然后需要剪枝,step>t||(t-step-abs(ex-x)-abs(ey-y))%2!=0这句是核心
程序代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int m,n,t,sx,sy,ex,ey,flag;
char str[10][10];
int book[10][10];
void dfs(int x,int y,int step);
int main()
{
int i,j,count;
while(scanf("%d%d%d",&m,&n,&t),m!=0||n!=0||t!=0)
{
flag=count=0;
memset(book,0,sizeof(book));
for(i=0;i<m;i++)
scanf("%s",str[i]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
if(str[i][j]=='S')
{
sx=i;
sy=j;
}
else if(str[i][j]=='D')
{
ex=i;
ey=j;
}
else if(str[i][j]=='X')
count++;
}
if(m*n-count>t)//由于不能重复的走,所以去掉墙剩下的路不能少于t步。
dfs(sx,sy,0);
if(flag==0)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
void dfs(int x,int y,int step)
{
int i,tx,ty;
int next[4][2]={0,1,1,0,0,-1,-1,0};
book[x][y]=1;
if(step>t||(t-step-abs(ex-x)-abs(ey-y))%2!=0||flag==1)
return;
if(str[x][y]=='D'&&step==t)
{
flag=1;
return;
}
for(i=0;i<4;i++)
{
tx=x+next[i][0];
ty=y+next[i][1];
if(tx<0||tx>m-1||ty<0||ty>n-1)
continue;
if(book[tx][ty]==0&&str[tx][ty]!='X')
{
dfs(tx,ty,step+1);
book[tx][ty]=0;//这句回溯不能忘
}
}
}