题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1010
Tempter of the Bone
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 131057 Accepted Submission(s): 35308
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.
'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.
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0
YES
代码如下:
#include<stdio.h>//hdu1010 dfs+奇偶性剪枝
#include<stdlib.h> char map[][];
int n,m,t, wall, si, sj, di, dj;
int d[][] = {{, }, {, -}, {, }, {-, }}; int dfs(int i, int j, int step)
{
if(step == t)//如果最后一秒
{ //判断是否到达door
if(i == di && j == dj) return ;
else return ;
} if (i == di && j == dj )//如果到达door
{
//判断是否最后一秒
if (step == t) return ;
else return ;
} //奇偶性剪枝
int temp = t-step-abs(i - di) + abs(j - dj);
if( temp% )
return ; for (int k = ; k<; k++)
{
int x = i + d[k][];
int y = j + d[k][];
if (x>= && x<=n && y>= && y<=m && map[x][y] != 'X')
{
map[x][y] = 'X';
if(dfs(x, y, step + )) return ;
map[x][y] = '.';//回溯出口,记得复原(可能把'D'变成'.',但已经用didj保存其位置,所以没关系)
}
}
return ;
} int main()
{
while(scanf("%d%d%d",&n,&m,&t) &&m &&n &&t)
{
wall = ;
for (int i = ; i<=n; i++)
{
scanf("%s",map[i]+);
for (int j = ; j<=m; j++)
{
//用scanf(%c) 就出问题?
if (map[i][j] == 'S') { si = i; sj = j; }
if (map[i][j] == 'D') { di = i; dj = j;}
if (map[i][j] == 'X') { wall++; }
}
} map[si][sj] = 'X';
if (n * m - wall- < t)
{ //初始判断剩余的空格(记得减去初始位置)是否够走
puts("NO");
continue;
} if (dfs(si, sj, ))
puts("YES");
else
puts("NO");
}
return ;
}