Tempter of the Bone
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 97047 Accepted Submission(s): 26333
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
Author
ZHANG, Zheng
Source
ZJCPC2004
上去大概一看题,果断认为是广搜(bfs)和优先队列求最小步数的题,以为很简单。然后就意料之中的WA了。
只好再次自习读题,原来题意是:在T时刻到达门D的位置,不能走走过的路,才知道是深搜(dfs)。粗略写了个代码就又交了,结果TLE。
去查了查才知道还需要剪枝,要不太费时间,用了剪枝后就AC了。
是个好题,看来以后还是要认真看题啊,即使是英语题。
代码如下:
#include
#include
using namespace std;
int movex[4]={0,0,1,-1};
int movey[4]={1,-1,0,0};
char map[11][11];
int stx,sty;
int endx,endy;
int W,H;
int T;
bool ans;
int check(int x,int y)
{
if (x<0 || x>=H || y<0 || y>=W)
return 1; //返回1不可移动
return 0;
}
int abs(int n)
{
if (n<0)
return -n;
return n;
}
void dfs(int x,int y,int stp)
{
if (check(x,y))
return;
if (ans)
return;
if (x==endx && y==endy && stp==T)
{
ans=true;
return;
}
int t;
t=abs(x-endx)+abs(y-endy);
t=T-t-stp;
if (t&1)
return; //剪枝处理
if (t<0)
return;
for (int i=0;i<4;i++)
{
if (map[x+movex[i]][y+movey[i]]!='X')
{
map[x+movex[i]][y+movey[i]]='X'; //走过的不能重复走,这一步漏了就错了,切记
dfs(x+movex[i],y+movey[i],stp+1);
map[x+movex[i]][y+movey[i]]='.';
}
}
}
int main()
{
int num; //墙的数量
while (scanf ("%d %d %d",&H,&W,&T) && (H || W || T))
{
num=0;
for (int i=0;i=T)
{
map[stx][sty]='X';
dfs(stx,sty,0);
}
if (ans)
printf ("YES\n");
else
printf ("NO\n");
}
return 0;
}