[HDU] [1010] Tempter of the Bone

Problem Description

Loading...

Problem Analysis

Given a map
ask whether the exit can be reached at the T-th second
Because this is not about finding the shortest distance, multiple recursions are needed
And because the number of recursions is huge
Pruning is required
Useful pruning ideas include

  • If a valid solution has already been found, all remaining recursions can stop
  • Record the total number of walkable ‘.’ cells; if tcnt+1<T then it is definitely impossible
  • Most importantly, prune based on Manhattan distance (the shortest path length between two points |x1-x2|+|y1-y2|). The path length (not necessarily shortest) and the shortest path length have the same parity, so their difference must be even. Therefore, check the parity of the Manhattan distance from the current position to the exit and the path length needed from it to the exit if a solution exists; if their difference is odd, recursion can stop.
cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdio.h>
int move[4]= {1,-1,0,0};
char map[10][10];
int cnt[10][10];
int H,W,T;
int sH,sW,eH,eW,se;
bool win;
int abs(int m) {
    return m>0?m:-m;
}
void dfs(int n,int m) {
    if(win)
        return ;
    int t=(T-cnt[n][m])-(abs(n-eH)+abs(m-eW));
    if(t<0||t&1)
        return ;
    if(n==eH&&m==eW&&cnt[n][m]==T)
        win=true;
    for(int i=0; i<4; i++) {
        int tn=n+move[i],tm=m+move[(i+2)%4];
        if(tn>=0&&tn<H&&tm>=0&&tm<W&&map[tn][tm]!='X'&&cnt[tn][tm]>cnt[n][m]+1&&cnt[n][m]<T) {
            cnt[tn][tm]=cnt[n][m]+1;
            dfs(tn,tm);
            cnt[tn][tm]=99999999;
        }
    }
}
int main() {
    while(scanf("%d %d %d",&H,&W,&T),H||W||T) {
        getchar();
        int tcnt=0;
        for(int i=0; i<H; i++) {
            for(int j=0; j<W; j++) {
                cnt[i][j]=99999999;
                map[i][j]=getchar();
                if(map[i][j]=='S')
                    sH=i,sW=j;
                else if(map[i][j]=='D')
                    eH=i,eW=j;
                else if(map[i][j]=='.')
                    tcnt++;
            }
            getchar();
        }
        if(tcnt+1<T) {
            printf("NO\n");
            continue;
        }
        se=abs(sH-eH)+abs(sW-eW);
        win=false;
        cnt[sH][sW]=0;
        dfs(sH,sW);
        printf("%s\n",win?"YES":"NO");
    }
    return 0;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...