zoukankan      html  css  js  c++  java
  • hdu 1010 Tempter of the Bone DFS+奇偶性剪枝

     
    给一个地图:
    'X': 障碍
    'S':狗的起始的位置
    'D':出口
    '.': 路
    要求刚好在T时间时到达出口,且路不可重走。输出是否能够完成。
    本题不宜用BFS,因为算的是恰好在T时间到达出口,并不是求最短时间。
    所以用DFS较好。
    当时间大于T时就不用考虑了,然后还要再奇偶性剪枝,进行优化。
     

    #include<stdio.h>
    #include<stdlib.h>
    #include<queue>
    #include<string.h>
    #include <iostream>
    using namespace std;
    char map[10][10];
    int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
    int co,ro,T,c,d,ans;
    bool judge(int x,int y,int step)
    {
        if(x<0||y<0||x>=co||y>=ro)
        return false;
        if(map[x][y]=='X')
        return false;
        if((abs(c-x)+abs(d-y))%2!=(T-step)%2||step>T)      //abs(c-x)+abs(d-y))%2!=(T-step)%2奇偶性剪枝
        return false;
        return true;
    }
        
    void dfs(int a,int b,int step)
    {
        int i,x,y;
        if(a==c&&b==d&&step==T)
        {
            ans=1;
            return;
        }
        if(ans)
        return;
        for(i=0;i<4;i++)
        {
            x=a+dir[i][0];
            y=b+dir[i][1];
            if(!judge(x,y,step+1))
            continue;
            map[x][y]='X';
            dfs(x,y,step+1);
            map[x][y]='.';
        }
    }
    int main()
    {
        int i,j,a,b;
        while(scanf("%d%d%d",&co,&ro,&T),co+ro+T)
        {
            for(i=0;i<co;i++)
            scanf("%s",map[i]);
            for(i=0;i<co;i++)
            for(j=0;j<ro;j++)
            {
                if(map[i][j]=='S')
                {
                    a=i;
                    b=j;
                }
                if(map[i][j]=='D')
                {
                    c=i;
                    d=j;
                }
            }
            ans=0;
            map[a][b]='X';
            dfs(a,b,0);
            if(ans)
            printf("YES\n");
            else
            printf("NO\n");
        }
        return 0;
    }

            
            
  • 相关阅读:
    Python学习心得第二周-作业
    Python学习心得第二周-02 字符串、列表、元组、字典
    Python学习心得第二周-01 数字类型
    eclipse 性能调优之内存分配
    Spring 面试
    技巧 linux 如何显示一个文件的某几行(中间几行)
    命令 scp
    机器学习遇到的好的资料
    maven 使用记录
    “冷启动”问题浅析
  • 原文地址:https://www.cnblogs.com/zxj015/p/2740271.html
Copyright © 2011-2022 走看看