迷宫搜索

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1010

 

奇偶性剪枝

 

可以把map看成这样: 

 

0 1 0 1 0 1 

1 0 1 0 1 0 

0 1 0 1 0 1 

1 0 1 0 1 0 

0 1 0 1 0 1 

 

从为0的格子走一步,必然走向为1的格子,从为1的格子走一步,必然走向为0的格子。 

 

即:

0 ->11->0 必然是奇数步          

0->0 1->1 必然是偶数步

 

所以当遇到从0走向0但是要求时间是奇数的,或者从1走向0但是要求时间是偶数的都可以直接判断不可达!

 

#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>

using namespace std;
const int N = 15;

char map[N][N];
int startx,starty,endx,endy;
int n,m,Time;
bool flag;

int dir[4][2] = {-1,0,1,0,0,-1,0,1};

void DFS(int x,int y,int t)
{
    if(flag) return;
    if(x == endx && y == endy && t == Time)
    {
        flag = 1;
        return;
    }
    int tmp = abs(x - endx) + abs(y - endy);
    if((Time - t) % 2 != tmp % 2) return;
    if(tmp > Time - t) return;
    for(int i=0;i<4;i++)
    {
        int tx = x + dir[i][0];
        int ty = y + dir[i][1];
        if(tx < n && tx >= 0 && ty < m && ty >= 0 && map[tx][ty] != 'X')
        {
            map[tx][ty] = 'X';
            t++;
            DFS(tx,ty,t);
            t--;
            map[tx][ty] = '.';
        }
    }
}

int main()
{
    while(cin>>n>>m>>Time)
    {
        if(n == 0 && m == 0 && Time == 0) break;
        int cnt = 0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                cin>>map[i][j];
                if(map[i][j] == 'S')
                {
                    startx = i;
                    starty = j;
                    map[i][j] = 'X';
                }
                else if(map[i][j] == 'D')
                {
                    endx = i;
                    endy = j;
                }
                else if(map[i][j] == '.') cnt++;
            }
        }
        if(cnt + 1 < Time)
        {
            puts("NO");
            continue;
        }
        flag = false;
        DFS(startx,starty,0);
        if(flag) puts("YES");
        else puts("NO");
    }
    return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值