#问题
Tempter of the Bone
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 146964 Accepted Submission(s): 39198
Problem 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
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
#这是一道很基础的DFS题目,需要运用到两个剪枝
1.DFS前,起点到终点的最近折线长度与要求的T的差值一定为偶数(这点可以在地图上比划,无论怎样绕圈子,奇偶性保持这种规律)
2.DFS中,如果目前步数超过要求的T,直接返回
#AC码
#include<iostream>
#include<string.h>
using namespace std;
int Map[8][8];
int N,M,T;
int cx,cy; //起点位置
int ex,ey; //终点位置
char ch;
int abs(int x)
{
if(x>0)
return x;
else
return -1*x;
}
int DFS(int x,int y,int cn) //函数返回1代表找到,其他任何情况均返回0
{
if(cn==T&&x==ex&&y==ey)
return 1;
if(cn>=T)
return 0;
if(Map[x+1][y]!=-1)
{
Map[x+1][y]=-1;
if(DFS(x+1,y,cn+1))
return 1;
else
Map[x+1][y]=0;
}
if(Map[x-1][y]!=-1)
{
Map[x-1][y]=-1;
if(DFS(x-1,y,cn+1))
return 1;
else
Map[x-1][y]=0;
}
if(Map[x][y+1]!=-1)
{
Map[x][y+1]=-1;
if(DFS(x,y+1,cn+1))
return 1;
else
Map[x][y+1]=0;
}
if(Map[x][y-1]!=-1)
{
Map[x][y-1]=-1;
if(DFS(x,y-1,cn+1))
return 1;
else
Map[x][y-1]=0;
}
return 0;
}
int main()
{
//freopen("1010.txt","r",stdin);
while(cin>>N>>M>>T,N)
{
//Map初始化
memset(Map,-1,sizeof(Map));
//录入
for(int i=1;i<=N;i++)
for(int j=1;j<=M;j++)
{
cin>>ch;
if(ch=='.')
Map[i][j]=0;
if(ch=='D')
{
ex=i;
ey=j;
Map[ex][ey]=0;
}
if(ch=='S')
{
cx=i;
cy=j;
}
}
if(((abs(cx-ex)+abs(cy-ey)-T)%2==0)&&DFS(cx,cy,0)) //与需要步数差为偶数
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}