zoj 2110 hdoj 1010 深度遍历+奇偶性剪枝

20 篇文章 0 订阅

题目大意:要你求一个迷宫中,起点s经过给定的步数是否能到终点t,迷宫中有挡板,挡板是不能走的格子

解题思路:很明显的搜索题,用深度优先或宽度优先遍历搜索是否满足,给定步数,也就是求起点根结点到终点最终解的那个搜索树经过的边树

深度优先遍历,要用到奇偶性剪枝,开始不知道啥叫。。。。奇偶性剪枝,

看了这哥们的博客才明白:

详情见:http://www.cppblog.com/Geek/archive/2010/04/26/113615.html

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

struct Point
{
    int x, y;
};

const int maxn = 8;
char maze[maxn][maxn];
bool map[maxn][maxn];

int n, m, t, step;
Point dir[4] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Point s, e;

bool dfs(int x, int y);

int main()
{
    
    while(true)
    {
        scanf("%d %d %d", &n, &m, &t);
        if(n == 0 && m == 0 && t == 0)
            break;
        memset(map, 0, sizeof(map));
        step = 0;
        for(int i = 0; i < n; i++)
        {
            char *p;
            scanf("%s", maze[i]);
            if ((p = strchr(maze[i], 'S')) != NULL)
            {
                s.x = i;
                s.y = p - maze[i];
            }
            if ((p = strchr(maze[i], 'D')) != NULL)
            {
                e.x = i;
                e.y = p - maze[i];
            }
        }
        if(dfs(s.x, s.y))
            printf("YES\n");
        else
            printf("NO\n");

    }
    
    return 0;
}

bool dfs(int x, int y)
{
    if(step > t)
        return false;
        
    int st = abs(x - y);
    int ed = abs(e.x - e.y);
    if(x >= 0 && x < n && y >= 0 && y < m && !map[x][y] && maze[x][y] != 'X' && (t - step - st - ed) % 2 == 0)
        map[x][y] = true;
    else
        return false;

    if(x == e.x && y == e.y && step == t)
        return true;

    
    for(int i = 0; i < 4; i++)
    {
        int dx = x + dir[i].x;
        int dy = y + dir[i].y;
        int tmp = step;
        step++;
        if(dfs(dx, dy))
            return true;
        step = tmp;
    }
    map[x][y] = false;
    return false;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值