题目描述
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;
‘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
题目大意
题目大意:有一个 N*M 的迷宫,包括起点 S,终点 D,墙 X,和地面,0 秒时主人公从 S 出发,每秒能走到四个与其相邻的位置中的一个,且每个位置被 行走之后都不能再次走入,问是否存在这样一条路径使主人公在 T 秒时刚好走到D。
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m,t;
int sx,sy,dx,dy;
int ans,cas;
bool mark[9][9];
char str[9][9];
int go[][2]={
1,0,
-1,0,
0,1,
0,-1
};
void DFS(int x,int y){
if(str[x][y]=='D'){
if(ans==t){cas++;return;}
else return;
}
for(int i=0;i<4;i++){
int nx=x+go[i][0];
int ny=y+go[i][1];
if(nx>n||nx<1||ny>m||ny<1)continue;
if(str[nx][ny]=='X')continue;
if(mark[nx][ny]==true)continue;
mark[nx][ny]=true;
ans++;
DFS(nx,ny);
ans--;
mark[nx][ny]=false;
}
return;
}
int main(void){
while(scanf("%d%d%d",&n,&m,&t)!=EOF){
for(int i=1;i<=n;i++)
scanf("%s",str[i]+1);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
mark[i][j]=false;
if(str[i][j]=='S'){sx=i;sy=j;}
}
ans=0;
cas=0;
DFS(sx,sy);
if(cas==0)printf("NO\n");
else printf("YES\n");
}
}
注意
DFS还可以再优化(如教程所示)