深度优先搜索+回溯法的题。关于路径存在性的问题,都考虑使用深度优先搜索+回溯法。
Debug记录:
①visit的时候忘记标记visited数组了导致超时
②关于使用scanf()录入%c:cin>>x无论x是啥类型,'\n' '\t' ' '(空白字符)不会被提取进x,一定会留在输入流中,当其后的字符被提取时其被丢弃。而对于scanf(“%口”,&x),其他的与cin一样,唯独x是char类型时,空白字符与其他字符一视同仁,也会被成功录入x中。
故在录入诸如“迷宫”类型的字符流(用二维数组存储)时,要避免使用scanf("%c")(输入流中的换行\n很难处理),可使用scanf("%s",buf[i]);整串录入。示例如下:
for (int i=0;i<n;i++){
scanf("%s",buf[i]);
}
-
题目描述:
-
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
-
提示:
-
用scanf读取输入。
#include <cstdio>
#define MAXSIZE 10
using namespace std;
int n,m,t,time;
bool suc;
char buf[MAXSIZE][MAXSIZE];
bool visited[MAXSIZE][MAXSIZE];
void DFS(int x,int y){
if ( (buf[x][y]!='X'&&0<=x&&x<n&&0<=y&&y<m)&&(visited[x][y]==false)&&suc==false/*这个suc也是为了剪枝,经测试没有此处的这个suc则直接超时*/)
{//指针非空(墙或者越界则空) 且没访问过
//visit
//要访问了
visited[x][y]=true;//访问标记
time++;//加完后为此刻时间
if (time==t){//
if(buf[x][y]=='D'){
suc=true;
}
}
//DFS
else{//time<t时才需要继续DFS (剪枝)
DFS(x-1,y);
DFS(x+1,y);
DFS(x,y-1);
DFS(x,y+1);
}
//上面已经遍历完此结点的所有子树了
//return(统一出口)
//回溯()
time--;
visited[x][y]=false;
return;
}
}
int main(){
while (scanf("%d%d%d",&n,&m,&t),n||m||t){
//initiate
time=-1;
suc=false;
//input & initiate visited[]
for (int i=0;i<n;i++){
scanf("%s",buf[i]);
for (int j=0;j<m;j++){
visited[i][j]=false;
}
}
//search
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if (buf[i][j]=='S'){
DFS(i,j);
break;
}
}
}
//output
printf("%s",suc?"YES\n":"NO\n");
}
return true;
}