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 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.
4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0
NOYES
思路:深搜寻找时间为特定时间的路径,这个题涉及了奇偶剪枝,我故意把它放在了深搜的外面,其实奇偶剪枝就是说:如果两个路径同起点,共终点,那么他们的时间差一定是偶数。其实很简单,以一条路径为基准,如果另一条偏离了他,假如他向上偏了一格,那么他迟早还会向下一格,因为他们最后重合,这是已知的,一上一下就当然是偶数了。其它方向类似。所以在dfs之前就可以剪枝了。
#include <cstdio> #include <cstring> #include <stack> #include <queue> #include <iostream> using namespace std; char mp[110][110]; int mark[110][110]; int m,n,xz,yz,T; int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; bool yes; void dfs(int x,int y,int t) { if(yes) return; if(t > T) return; if(mp[x][y] == 'D') { if(t == T) yes = 1; return; } for(int i = 0; i < 4; i++) { int x_ = x+dir[i][0]; int y_ = y+dir[i][1]; if(x_ < 1 || x_ > m || y_ < 1 || y_ > n) continue; if(mp[x_][y_] == 'X') continue; if(mark[x_][y_] == 1) continue; mark[x_][y_] = 1; dfs(x_,y_,t+1); mark[x_][y_] = 0; } } int main() { while(cin >> m >> n >> T&&m+n+T) { int x,y; memset(mark,0,sizeof(mark)); for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { cin >> mp[i][j]; if(mp[i][j] == 'S') x = i, y = j; if(mp[i][j] == 'D') xz = i,yz = j; } } mark[x][y] = 1,yes = 0; int tmp = xz-x+yz-y-T;//剪枝 if(tmp%2) { printf("NO\n"); continue; } dfs(x,y,0); printf(yes?"YES\n":"NO\n"); } return 0; }