hdu 1010 Tempter of the Bone

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

题意:从S走到D恰好t步,可以:YES  不可以:NO

分类:DFS

解题思路:深搜,需要做很多的优化,不然会超时,详情看代码

程序

#include<bits/stdc++.h>

using namespace std;

int n,m,t;

char ch[10][10];

int x[4]={1,0,-1,0}; 
int y[4]={0,1,0,-1};

int st_x,st_y;
int en_x,en_y;

int ans=0;

bool ok;

void bfs(int cur_x,int cur_y)
{
    ch[cur_x][cur_y]='X';

    if(ans==t)
    {
        if(cur_x==en_x&&cur_y==en_y)
            ok=1;
        return ;
    }

    if(abs(cur_x-en_x)+abs(cur_y-en_y)+ans>t)
     return;

    if((abs(cur_x-en_x)+abs(cur_y-en_y)+t-ans)%2)
     {
         return;
     }
    for(int i=0;i<4;i++)
    {
        if(ch[cur_x+x[i]][cur_y+y[i]]=='.'||
           ch[cur_x+x[i]][cur_y+y[i]]=='D'&&
           cur_x+x[i]<=n&&cur_y+y[i]<=m&&cur_x+x[i]>=1&&cur_y+y[i]>=1)
        {
            ch[cur_x+x[i]][cur_y+y[i]]='X';
            ans++;

            bfs(cur_x+x[i],cur_y+y[i]);
            if(ok) return;

            ans--;
            ch[cur_x+x[i]][cur_y+y[i]]='.';
        }
       // else

    }
}

int main()
{
    int sum=0;
    while(scanf("%d %d %d",&n,&m,&t)&&(n+m+t))
    {
        sum=0;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                cin>>ch[i][j];
                if(ch[i][j]=='S')
                {
                    st_x=i;
                    st_y=j;
                }
                else if(ch[i][j]=='D')
                {
                    en_x=i;
                    en_y=j;
                }
                else if(ch[i][j]=='X')
                {
                    sum++;
                }
            }
        }


         ok=0;

         if(n*m-sum<=t||(abs(en_x-st_x)+abs(en_y-st_y)+t)%2) 
         {
             printf("NO
");
             continue;
         }
         ans=0;
             bfs(st_x,st_y);
         if(ok) printf("YES
");
         else printf("NO
");
    }

    return 0;
}
anytime you feel the pain.hey,refrain.don't carry the world upon your shoulders
原文地址:https://www.cnblogs.com/gaoss/p/4908861.html