HDU - 1010 Tempter of the Bone(奇偶性剪枝DFS)

题目链接
一开始审题不认真,以为是BFS.认真看了之后其实应该是DFS.想不TLE还得会奇偶性剪枝.关于奇偶性剪枝这个博客讲的很不错.
附上代码(好久没敲搜索题了,不是很简洁)

#define LL long long
#define pb push_back
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
#include <string>
#include <cstdio>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
using namespace std;
struct Node {
    int r, c, cost;
};
const int N = 10;
char maze[N][N];
bool vis[N][N];
int dr[4] = { 1,-1,0,0 };
int dc[4] = { 0,0,1,-1 };
int n, m, t;
bool inside(int r, int c) {
    if (r >= 1 && r <= n && c >= 1 && c <= m) return true;
    return false;
}
int r1, r2, c1, c2;
bool f = 0;
bool dfs(int sr, int sc, int ct) {
    if (f) return true;
    if (sr == r2 && sc == c2 && ct == t) {
        f = 1;
        return true;
    }
    if (ct >= t) return false;
    if ((abs(r2 - sr) + abs(c2 - sc)) > t - ct) return false;
    if ((abs(r2 - sr) + abs(c2 - sc)) % 2 != (t - ct) % 2) return false;
    for (int i = 0; i < 4; ++i) {
        if (!inside(sr + dr[i], sc + dc[i])) continue;
        if (maze[sr + dr[i]][sc + dc[i]] == 'X') continue;
        if (vis[sr + dr[i]][sc + dc[i]]) continue;
        vis[sr + dr[i]][sc + dc[i]] = 1;
        if (dfs(sr + dr[i], sc + dc[i], ct + 1)) return true;
        else vis[sr + dr[i]][sc + dc[i]] = 0;
    }
    return false;
}
int main() {
    ios::sync_with_stdio(false);
    while (cin >> n >> m >> t) {
        if (!(n + m + t)) break;
        f = 0;
        memset(vis, 0, sizeof(vis));
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= m; ++j) {
                cin >> maze[i][j];
                if (maze[i][j] == 'S') r1 = i, c1 = j;
                if (maze[i][j] == 'D') r2 = i, c2 = j;
            }
        }
        vis[r1][c1] = 1;
        if (dfs(r1, c1, 0)) cout << "YES\n";
        else cout << "NO\n";
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45590210/article/details/104948184
今日推荐