ZOJ 2110 Tempter of the Bone

12 篇文章 0 订阅
5 篇文章 0 订阅

题意:在迷宫里,'X'表示墙,'S'表示起点,'D'表示终点,'.' 表示路,在起点处有一条狗,每秒可以移动一格,多组数据,每组第一行有三个数据,分别为迷宫的宽度和高度,与时间,判断这条狗是否能走出迷宫。

链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1110

思路:因为迷宫范围比较小,可以用DFS搜索,因为要时间恰好为t秒,因此要用回溯法判断是否能在t秒是恰好到达'D'位置。

注意点:因为需时间恰好为t,因此需要在到达'D'位置时判断时间。

以下为AC代码:

Run IDSubmit TimeJudge StatusProblem IDLanguageRun Time(ms)Run Memory(KB)User Name
37785702014-09-22 20:40:31Accepted 2110C++0x200272luminus

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;

struct node
{
    int x;
    int y;
};

bool flag;
struct node be;
struct node en;
int m, n, t;
char map[10][10];
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };

void dfs ( int x, int y, int time )
{
    if ( x == en.x && y == en.y )
    {
        if ( t == time )
        {
           flag = true;
           return;
        }
        else
        {
            return;
        }
    }
    for ( int i = 0; i < 4; i ++ )
    {
        map[x][y] = 'X';
        if ( map[x + dir[i][0]][y + dir[i][1]] == '.' )
        {
            dfs ( x + dir[i][0], y + dir[i][1], time + 1 );
            if ( flag )
            {
                return;
            }
        }
        map[x][y] = '.';
    }
}

bool judge ( int t )
{
    int xi = abs ( be.x - en.x );
    int yi = abs ( be.y - en.y );
    if ( ( xi + yi ) % 2 == t % 2 )
    {
        return true;
    }
    else
    {
        return false;
    }
}

int main()
{
    while ( cin >> m >> n >> t )
    {
        if ( ! m && ! n && ! t )
        {
            return 0;
        }
        memset ( map, 'X', sizeof ( map ) );
        flag = false;
        cin.ignore();
        for ( int i = 1; i <= m; i ++ )
        {
            for ( int j = 1; j <= n; j ++ )
            {
                cin >> map[i][j];
                if ( map[i][j] == 'S')
                {
                    be.x = i;
                    be.y = j;
                    map[i][j] = 'X';
                }
                else if ( map[i][j] == 'D' )
                {
                    en.x = i;
                    en.y = j;
                    map[i][j] = '.';
                }
            }
        }
        if ( judge ( t ) )
        {
            dfs ( be.x, be.y, 0 );
        }
        if ( flag )
        {
            cout << "YES" << endl;
        }
        else
        {
            cout << "NO" << endl;
        }
    }
    return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值