Description
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
'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‘表示在T秒到达
如果可以在T秒内到达,则输出'YES',否则就输出’NO'。
解题思路:先用递归到要走的终点,如果中途不通则回溯(这里要用到奇偶减枝,否则会超时),然后计算出总共的时间,如果时间在T秒内则说明可以,否则不行。
代码
#include<stdio.h>
char a[100][100];
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
int n, m, t, sx, sy, ex, ey;
int i, j, num, key;
void dfs(int nx,int ny,int sum)
{
int k, nextx, nexty, u, v;
if(nx==ex &&ny==ey && sum==t)
key=1;
if(key)
return;
u=ex-nx;
v=ey-ny;
if(u<0)
u=-u;
if(v<0)
v=-v;
if((u+v)%2!=(t-sum)%2) //奇偶减枝
return;
for(k=0; k<4; k++)
{
nextx=nx+dir[k][0];
nexty=ny+dir[k][1];
if(nextx>=0 && nextx<n && nexty>=0 && nexty<m && a[nextx][nexty]!='X')
{
a[nextx][nexty]='X';
dfs(nextx,nexty,sum+1);
a[nextx][nexty]='.'; //如果此路不通则回溯到上一层
}
}
}
int main()
{
while(scanf("%d%d%d", &n, &m, &t)!=EOF)
{
getchar();
if(n==0&&m==0&&t==0)
break;
key=0;
num=0;
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
scanf("%c", &a[i][j]);
if(a[i][j]=='S')
{
sx=i; sy=j;
}
else if(a[i][j]=='D')
{
ex=i; ey=j; num++;
}
else if(a[i][j]=='.')
{
num++;
}
}
getchar();
}
a[sx][sy]='X';
if(num>=t)
dfs(sx, sy, 0);
if(key)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}