hdu 1010 Tempter of the Bone 搜索

難度:3

算法:搜索dfs

題目大意:一隻狗要吃骨頭,結果進入了一個迷宮陷阱,迷宮裏每走過一個地板費時一秒,該地板就會在下一秒塌陷,所以你不能在該地板上逗留。迷宮裏面有一個門,只能在特定的某一秒才能打開,讓狗逃出去。現在題目告訴你迷宮的大小和門打開的時間,問你狗可不可以逃出去,可以就輸出YES,否則NO。

 
這道題考慮搜索的減枝。
減枝的條件是:
1.如果可走地板數目小於給定的時間,絕對不可能得救。

2.狗走到門的時間必須和題目給定的時間是同奇同偶的,否則也不能在指定的那秒到達門,也不可能得救

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10;
char ch[maxn][maxn];
int n , m , t;
bool vis[maxn][maxn];
int sx , sy , ex , ey;
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
bool inmap(int x,int y) {
    return x >= 0 && x < n && y >= 0 && y < m;
}
bool check1(int x,int y,int ct) {
    return abs(x-ex) + abs(y-ey) + ct <= t;
}
bool check2(int x,int y,int ct) {
    return (abs(x-ex) + abs(y-ey)) % 2 == (t - ct) % 2;
}
bool init() {
    for(int i=0;i<n;i++) scanf("%s" , ch[i]);
    memset(vis , false , sizeof(vis));
    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++) {
        if(ch[i][j] == 'S') sx = i , sy = j;
        if(ch[i][j] == 'D') ex = i , ey = j;
    }
}
bool dfs(int x,int y,int ct) {
    if(ct > t) return false;
    if(ct == t) {
        if(ch[x][y] == 'D') return true;
        return false;
    }
    if(!check1(x , y , ct)) return false;
    if(!check2(x , y , ct)) return false;
    vis[x][y] = true;
    for(int i=0;i<4;i++) {
        int xx = x + dir[i][0];
        int yy = y + dir[i][1];
        if(!inmap(xx , yy) || vis[xx][yy] || ch[xx][yy] == 'X') continue;
        if(dfs(xx , yy , ct+1)) return true;
    }
    vis[x][y] = false;
    return false;
}
int main() {
    while(~scanf("%d%d%d" , &n,&m,&t) && n+m+t) {
        init();
        if(!dfs(sx , sy , 0)) puts("NO");
        else puts("YES");
    }
    return 0;
}


發佈了45 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章