dfs奇偶剪枝---HDU - 1010

题意:问小狗是否能在第T秒(走T步)从S点到达D点

思路:很明显的一道dfs题目,但是我们这里需要采用剪枝减少不必要的路,另外这里的地图是字符,我们输入需要注意吸收换行符

另外如果找到了答案,我们用全局变量把它标记,只要它找到了答案,后面的操作不用进行

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
char c[10][10];
int fx[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int T,flag=0;
int N,M,ffx,ffy;
void dfs(int s,int e,int step)
{
    //写法一
    if(s==ffx&&e==ffy&&step==T)
    {
        flag=1;
    }
    if(flag==1)  //表示后面都不需要进行下去
    return;
    
    /*写法二
    if(s==ffx&&e==ffy&&step==T)
    {
        flag=1;
        return;//这个会TLE   进行很多无用操作
    }
    */
    
    if(s<0||e<0||s>=N||e>=M)
    return;

    int ans=T-step-abs(ffx-s)-abs(ffy-e); //奇偶剪枝
    if(ans<0||ans&1)
    return;

    for(int i=0; i<4; i++)
    {
        int tx=fx[i][0]+s;
        int ty=fx[i][1]+e;
        if(c[tx][ty]!='X')
        {
            c[tx][ty]='X';
            dfs(tx,ty,step+1);
            c[tx][ty]='.';
        }
    }
}
int main()
{
    while(scanf("%d%d%d",&N,&M,&T)!=EOF)
    {
        getchar();//吸收换行符
        if(N==0&&M==0&&T==0)
            break;
        int s=0,e=0;
        for(int i=0; i<N; i++)
        {
            for(int j=0; j<M; j++)
            {
                scanf("%c",&c[i][j]);
                if(c[i][j]=='S')
                {
                    s=i,e=j;
                }
                if(c[i][j]=='D')
                {
                    ffx=i,ffy=j;
                }
            }
            getchar();//吸收换行符
        }
        int step=0;
        flag=0;
        c[s][e]='X';
        dfs(s,e,step);
        if(flag==1)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/Aiahtwo/p/11296366.html