HDU - 1010 Tempter of the Bone DFS + 细节剪枝

1.题意:给出n行m列的迷宫,其中S代表起点,D代表出口,X表示墙(无法通过),'  .  '表示空地,出口在t时刻会打开,问你能否在门打开的时候逃出去。

2.分析:

第一次当成BFS来做了,求的是到达出口时间<=t即可逃出,WA

第二次发现题目说的是在t时刻门才打开,所以转为DFS深搜有没有到达出口时间恰好为t的路径,TLE

第三次用曼哈顿距离剪枝,TLE

无限TLE

最后发现我距离正确答案差了一句 : if(a==ex&&b==ey&&step!=t)return false;

发现自己一个大漏洞:如果有到达出口但是没有时间恰好等于t时,这时候不可能有结果了应该立刻结束,否则我的程序还会继续在出口往四周进行没有意义的深搜,大大浪费了时间!所以写DFS结束时要注意结束没有结果的过程!

3.代码:

#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<cmath>
using namespace std;
const int maxn = 10000  + 10;
char maps[10][10];
bool judge[10][10];
int n,m,t;
int sx,sy,ex,ey;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
bool DFS(int a,int b,int step)
{
     if(a==ex&&b==ey&&step==t){
            return true;
     }
     if(step>t||(a==ex&&b==ey))return false;//结束过程
     for(int i = 0;i<4;i++){
        int fx = a+dx[i];
        int fy = b+dy[i];
        if(fx>=0&&fx<n&&fy>=0&&fy<m&&maps[fx][fy]!='X'&&!judge[fx][fy]){
            judge[fx][fy] = 1;
            if(DFS(fx,fy,step+1))return true;
            judge[fx][fy] = 0;
        }
     }
     return false;
}
int main()
{
    while(scanf("%d%d%d",&n,&m,&t)!=EOF&&(n||m||t)){
        memset(judge,0,sizeof(judge));
        ex = ey = -1;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>maps[i][j];
                if(maps[i][j]=='S'){sx = i;sy = j;}
                else if(maps[i][j]=='D'){ex = i;ey = j;}
            }
        }
        judge[sx][sy] = 1;
        if(DFS(sx,sy,0))printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40772692/article/details/81481278