HDU - 1010 (Tempter of the Bone) (dfs + pruning)

Meaning: Give n*m matrices,'S'stands for the starting point,'D' is the door, the door is only in the t second,'X'is the roadblock, can not pass,'.' can pass, ask if you can reach'D'in the t second. Moreover,'S'and'D' have only one in the graph.
Analysis: dfs, at first thought of as bfs, no, BFS has been labeled after the attempt, can not remove the label, DFs in the attempt found that can not go through the label can be removed. There is also the need to prune, parity pruning, if the end point to the beginning of the distance is odd, but time is even, or time is odd, distance is even, can not reach. If it is not cut, it will be TL.
The code is as follows:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<vector>
#include<set>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
int n,m,t;
int x3,y3,x2,y2;
int vis[105][105];
char Map[105][105];
int flag=0;
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//Directional array
bool dfs(int x,int y,int cur)
{

    if(x==x2&&y==y2&&cur==t)  //The condition of arrival, if arrived, flag is 1;
    {
        flag=1;
        return true;

    }
       if(x==x2&&y==y2)      //Return Kit
        return true;
        //Four Directions of Attempt 
        for(int i=0;i<4;i++)
        {
            int dx=x+d[i][0];
            int dy=y+d[i][1];
            if(dx>=0&&dx<n&&dy>=0&&dy<m&&!vis[dx][dy]&&Map[dx][dy]!='X')
            {
                vis[dx][dy]=1;//Marked as gone
                dfs(dx,dy,cur+1);


                vis[dx][dy]=0;//If returned, remove the mark
            }
        }

}
int main()
{
    while(scanf("%d%d%d",&n,&m,&t)!=EOF&&n&&m&&t)
    {
        for(int i=0;i<n;i++)
            scanf("%s",Map[i]);

  //Find the starting point and the end point
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
        {
            if(Map[i][j]=='S')
            {
                x3=i;
                y3=j;
            }
            if(Map[i][j]=='D')
            {
                x2=i;
                y2=j;
            }
        }
        memset(vis,0,sizeof(vis));
        if(abs(x2-x3)+abs(y2-y3)>t||(abs(x2-x3)+abs(y2-y3))%2!=t%2)//Prune
        cout<<"NO"<<endl;
        else
        {
            vis[x3][y3]=1;
        flag=0;
        dfs(x3,y3,0);
        if(flag)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
        }

    }
}

Posted by shortkid422 on Sat, 09 Feb 2019 08:30:19 -0800