hdu Tempter of the Bone(DFS + 枝减)

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

大意:在一个坐标内,给定起点和终点,问能否恰好在t时刻到达终点。

刚好到达问题,嘿嘿,有意思。不考虑广搜了,用深搜:
因为有标记tag,及时地跳出不做无用功,用奇偶枝减提高效率。看看这里的奇偶枝减是怎么回事儿:
hdu Tempter of the Bone(DFS + 枝减)_第1张图片
代码:

#include <iostream>
#include <cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,m,k;
char s[7][7];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int ex,ey,sx,sy;
int abs(int a){
    if(a<0)a=a*(-1);
    return a;
}
int res=0,tag=0;
void dfs(int x,int y){
    if(tag==1)return ;
    for(int i=0;i<4;i++){
        int tx=x+dir[i][0],ty=y+dir[i][1];
        if(tx<n&&tx>=0&&ty<m&&ty>=0&&s[tx][ty]=='D'){
             if(res+1==k) {
                 tag=1;
                 return ;
            }
        }
        else if(tx<n&&tx>=0&&ty<m&&ty>=0&&s[tx][ty]=='.'){
            int q2=abs(tx-ex)+abs(ty-ey);
             if(abs(q2-(k-(res+1)))%2!=0) continue;
             s[tx][ty]='X';
             res++;
             dfs(tx,ty);
             s[tx][ty]='.';
             res--;
        }
    }
}
int main()
{
   //freopen("cin.txt","r",stdin);
   while(cin>>n>>m>>k){
       if(n==0)break;
       tag=0;
       res=0;
       getchar();
       for(int i=0;i<n;i++){
           for(int j=0;j<m;j++){
               scanf("%c",&s[i][j]);
               if(s[i][j]=='S'){  sx=i;  sy=j;  }
               if(s[i][j]=='D'){  ex=i; ey=j; }
           }
           getchar();
       }
       if(sx==ex&&sy==ey){ printf("YES\n"); continue;  }
       if(abs(sx-ex)+abs(sy-ey)>k) { printf("NO\n"); continue; }
       dfs(sx,sy);
       if(tag)printf("YES\n");
       else printf("NO\n");
   }
    return 0;
}
还能写的更简洁。。。


你可能感兴趣的:(DFS,HDU,枝减)