HDU 1010 Tempter of the Bone

http://acm.hdu.edu.cn/showproblem.php?pid=1010

题目读完一开始以为是BFS的题目,求一个最短路然后计算时间...

后来发现不对= =一定要正好到达出口的时候时间也吻合才能出去

所以是DFS...

一道比较基础的DFS,但是需要剪枝= =(一开始TLE了两次,才觉得需要剪枝,蠢哭)

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
using namespace std;
char map[10][10];
int ex,ey,sx,sy;
int n,m,t,wall;
bool flag;
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
void dfs(int x,int y,int cnt)
{
    if(cnt==t)
    {
        if(ex==x&&ey==y)
            flag=true;
        return;
    }
    if(flag)
        return;
    int temp=abs(x-ex)+abs(y-ey)-abs(cnt-t);//奇偶性剪枝,计算当前的离出口的距离
    if(temp>0||temp&1)//位运算判断奇偶性
        return;
    for(int i=0;i<4;i++)
    {
        int fx=x+dir[i][0];
        int fy=y+dir[i][1];
        if(fx>=0&&fx<n&&fy>=0&&fy<m&&map[fx][fy]!='X')
        {
            map[fx][fy]='X';
            dfs(fx,fy,cnt+1);
            map[fx][fy]='.';//回溯
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    while(scanf("%d%d%d",&n,&m,&t)!=EOF)
    {
        flag=false;
        wall=0;
        if(m==0&&n==0&&t==0)
            break;
        getchar();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%c",&map[i][j]);
                if(map[i][j]=='S')
                {
                    sx=i;
                    sy=j;
                    map[i][j]='X';
                }
                else if(map[i][j]=='D')
                {
                    ex=i;
                    ey=j;
                }
                else if(map[i][j]=='X')
                    wall++;
            }
            getchar();
        }
        if(m*n-wall<=t)
            flag=false;
        else
            dfs(sx,sy,0);
        if(flag)
            printf("YES\n");
        else
            printf("NO\n");


    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值