Tempter of the Bone HDU - 1010 DFS+剪枝

求迷宫中是否有路径长为t的起点到终点的路径。
一开始没有看清题意,以为是否有t长度内的路径,直接想到最短路径BFS。
BFS适合解决的问题类型

  1. 结点A出发到结点B是否有解?
  2. 结点A出发到结点B的路径哪条最短?(最短路)

然而很快WA了。此题不能使用BFS,因为是求是否有路径长为t的解。用BFS无法深入每一条路径。接着,我想想到BFS,深搜每一条路径,并记录路径长度再与t进行比较。没有剪枝的暴力深搜TLE了。
在这里插入图片描述
只有考虑有什么方式可以剪枝。
设搜索过程中的已用步数为step
首先可以想到 如果step>=t且未达到终点,就可以回溯。

进一步思考。因为给出了定解t,那么当前剩下的步数为t - step,我们可以判断剩下步数与最小到达步数的关系。
在这里插入图片描述
起点为黄色,终点为红色,起点到终点的最短步数必定是abs(dy - sy) + abs(dx - sx)。如果该值大于剩下步数,那么当前点无论如何怎么走,都到达不了终点。

最后就是搜索中的奇偶剪枝,奇偶剪枝平移路径即可证明得到绕行后路径-最短路径为偶数。

#include <iostream>
#include <cstring>
#include <cmath>
#define _for(i, a, b) for (int i = (a); i < (b); ++i)
using namespace std;
const int MAXN = 10;
char maze[MAXN][MAXN];
int vis[MAXN][MAXN];
int n, m, t;
int sx, sy;//起点
int gx, gy;//终点
//方向矢量
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int dfs(int x, int y, int step)
{
    if (x == gx && y == gy && step == t) return 1;
    if (step >= t) return 0;
    int mindis = abs(gx - x) + abs(gy - y);
    if (mindis > t - step) return 0;
    if ((mindis - t + step) % 2 != 0) return 0;//奇偶剪枝
    _for (i, 0, 4)
    {
        int nx = x + dx[i];
        int ny = y + dy[i];
        if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != 'X' && !vis[nx][ny])
        {
            vis[nx][ny] = 1;
            if (dfs(nx, ny, step+1)) return 1;
            vis[nx][ny] = 0;
        }
    }
    return 0;
}
void input()
{
    _for (i, 0, n)  _for(j, 0, m)
    {
        cin >> maze[i][j];
        if (maze[i][j] == 'S') {sx = i; sy = j;}
        else if (maze[i][j] == 'D') {gx = i; gy = j;}
    }
}
int main()
{
    while (cin >> n >> m >> t)
    {
        if (n == 0 && m == 0 && t == 0) break;
        input();
        memset(vis, 0, sizeof(vis));
        vis[sx][sy] = 1;//起点已被访问
        if (dfs(sx, sy, 0)) cout << "YES\n";
        else cout << "NO\n";
    }
    return 0;
}

发布了51 篇原创文章 · 获赞 19 · 访问量 8294

猜你喜欢

转载自blog.csdn.net/WxqHUT/article/details/99436110
今日推荐