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
NO
YES
#include "iostream"
#include "cstring"
using namespace std;
char maze[7][7];
bool ok[7][7];
int M,N,T; //界定边界
int flag = 0; //确定能否逃离
void dfs(int i,int j,int time) { //i,j为坐标,time 为到达此点所用时间
if(flag||time > T) return; //已经yes或者时间超过T,则退出
else if(time == T) { //时间为T,判断此处是否为D,是则flag = 1;不论是否,都return
if(maze[i][j] == 'D') flag = 1;
return;
}
else if(maze[i][j] == '.'|| maze[i][j] == 'S'){ //满足条件则进一步dfs
ok[i][j] = 1;//标记当前位置
//下一步要在定义域内且ok为0
if(i+1 >= 0 && i+1 < N && j >= 0 && j < M && !ok[i+1][j]) dfs(i+1,j,time+1);
if(i-1 >= 0 && i-1 < N && j >= 0 && j < M && !ok[i-1][j]) dfs(i-1,j,time+1);
if(i >= 0 && i < N && j+1 >= 0 && j+1 < M && !ok[i][j+1]) dfs(i,j+1,time+1);
if(i >= 0 && i < N && j-1 >= 0 && j-1 < M && !ok[i][j-1]) dfs(i,j-1,time+1);
ok[i][j] = 0; //还原ok,此处是关键
}
}
int main(){
ios::sync_with_stdio(false);
while(cin >> N >> M >> T) {
if(!N && !M && !T) break;
memset(ok,0,sizeof(ok));
int n,m,dx,dy;
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++) {
cin >> maze[i][j];
if(maze[i][j] == 'S') {
n = i;
m = j;
}
}
dfs(n,m,0);
if(flag) cout << "YES" << endl;
else cout << "NO" << endl;
flag = 0;
}
return 0;
}