首页 > 代码库 > hdu1010 - dfs,奇偶剪枝

hdu1010 - dfs,奇偶剪枝

题目链接

给一个迷宫,问从起点到终点存不存在一条长度为T的路径。

-----------------------------------------------------------------------------

技术分享

判断(T-当前步数)的奇偶性 和 (终点-当前位置)距离的奇偶性是否相同。

#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>

#define MAX(a,b) ((a)>=(b)?(a):(b))
#define MIN(a,b) ((a)<=(b)?(a):(b))
#define OO 0x0fffffff
typedef long long LL;
using namespace std;
const int N = 8;
const int skip[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };

int m, n, t;
int sx, sy, ex, ey;
char maze[N][N];
bool vis[N][N];
bool judge(int x, int y){
    if (x<0 || y<0 || x >= m || y >= n) return false;
    if (vis[x][y]) return false;
    if (maze[x][y] == X) return false;
    return true;
}

bool dfs(int x, int y, int step){
    if (x == ex&&y == ey&&step == t) return true;
    int tag = t - step - abs(ex-x) - abs(ey-y);
    if(tag<0||tag&1) return false;
    for (int i = 0; i<4; i++){
        int tx = x + skip[i][0];
        int ty = y + skip[i][1];
        if (judge(tx, ty)){
            vis[tx][ty] = true;
            if (dfs(tx, ty, step + 1)) return true;
            vis[tx][ty] = false;
        }
    }
    return false;
}


int main(){
    while (scanf("%d%d%d", &m, &n, &t), m + n + t){
        for (int i = 0; i<m; i++) {
            scanf("%s", maze[i]);
            for (int j = 0; j<n; j++){
                if (maze[i][j] == D) sx = i, sy = j;
                if (maze[i][j] == S) ex = i, ey = j;
            }
        }
        memset(vis, false, sizeof(vis));

        if (dfs(sx,sy,0)) puts("YES");
        else puts("NO");
    }
    return 0;
}

 

hdu1010 - dfs,奇偶剪枝