2013
11-26

# 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.

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.

For each test case, print in one line "YES" if the doggie can survive, or "NO" otherwise.

4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0

NO
YES

http://acm.hdu.edu.cn/showproblem.php?pid=1010

DFS + 多重剪枝(奇偶性剪枝)

#include<iostream>
#include<cmath>
using namespace std;
char map[10][10];
int flag, Xnum, Sx, Sy, Dx, Dy;
int n, m, t;
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

void DFS(int x, int y, int time)
{
if (x<=0 || x>n || y<=0 || y>m) return;
if (flag == 1) return;  //1.马上中断
if (x == Dx && y == Dy && time == t)
{
if(time == t)
flag = 1;
return;
}

int temp = (t - time) - abs(x - Dx) - abs(y - Dy);//2.奇偶性剪枝
if(temp<0 || temp & 1)  return;

for (int i = 0; i<4; i++)
{
int x1 = x + dir[i][0];
int y1 = y + dir[i][1];
if (map[x1][y1] != 'X')
{
map[x1][y1] = 'X';
DFS(x1, y1, time + 1);
map[x1][y1] = '.';
}
}
return;
}

int main()
{
while (cin>>n>>m>>t)
{
if(n==0&&m==0&&t==0) break;
Xnum = 0;
for (int i = 1; i<=n; i++)
{
for (int j = 1; j<=m; j++)
{
cin>>map[i][j];
if (map[i][j] == 'S')
{
Sx = i;
Sy = j;
}
if (map[i][j] == 'D')
{
Dx = i;
Dy = j;
}
if (map[i][j] == 'X')
Xnum ++;
}
}
flag = 0;
map[Sx][Sy] = 'X';

if (n * m - Xnum <= t)//3.提前判断t过大的情况避免再去搜，写上由500MS降到46MS
{
cout<<"NO"<<endl;
continue;
}
DFS(Sx, Sy, 0);
if (flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}

1. 我还有个问题想请教一下，就是感觉对于新手来说，递归理解起来有些困难，不知有没有什么好的方法或者什么好的建议？