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.
I/O
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.
Algorithm
DFS
Hint
DFS模板题,有几点注意。
- getchar()消去输入中的换行符
- 开一个大数组,从maze[1][1]开始读取,并初始化为X,可避免搜索时判断边界
剪枝。不剪枝是会TLE的,具体剪枝:
int temp = 0;
temp = len- abs(dx - x) - abs(dy - y);
if(temp < 0 || temp & 1)
return;if((abs(dx-sx)+abs(dy-sy))%2 != (t)%2)
printf(“NO\n”);
均通过判断步长奇偶性来实现。
Code
#include<cstdio>
#include<cmath>
#include<cstring>
int dir_x[4] = {1,-1,0,0};
int dir_y[4] = {0,0,1,-1};
int n, m, t, sx, sy, dx, dy;
char maze[9][9];
bool flag;
void dfs(int x, int y,int len)
{
int temp = 0;
temp = len- abs(dx - x) - abs(dy - y);
if(temp < 0 || temp & 1)
return;
for(int i = 0; i<4 && flag == 0 && len>0; i++)
{
if(maze[x+dir_x[i]][y+dir_y[i]] == '.')
{
maze[x+dir_x[i]][y+dir_y[i]] = 'X';
dfs(x+dir_x[i], y+dir_y[i], len-1);
maze[x+dir_x[i]][y+dir_y[i]] = '.';
}
if(x+dir_x[i] == dx && y+dir_y[i] == dy && len == 1)
{
flag = 1;
return;
}
}
return;
}
int main()
{
while(scanf("%d%d%d",&n, &m, &t) == 3)
{
getchar();
memset(maze, 'X', sizeof(maze));
if(n+m+t == 0)
break;
for(int i = 1; i<=n; i++)
{
for(int j = 1; j<=m; j++)
{
scanf("%c",&maze[i][j]);
if(maze[i][j] == 'S')
{
sx = i;
sy = j;
}
if(maze[i][j] == 'D')
{
dx = i;
dy = j;
}
}
getchar();
}
flag = 0;
if((abs(dx-sx)+abs(dy-sy))%2 != (t)%2)
printf("NO\n");
else
{
maze[sx][sy] = 'X';
dfs(sx, sy, t);
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}