HDU 1072 Nightmare BFS

/*
----------------------------------------------
        ACMer: Johnsondu
        Time: 19:45 - 20:13 2012.2.13
        Stratege: BFS , 多开一个二维数组,进行存储当前
                  坐标所剩下的时间,好进行对比
            
        Problem : 1072 ( Nightmare )     Judge Status : Accepted
        RunId : 5349088    Language : G++    Author : a312745658
-----------------------------------------------
*/

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std ;

#define INF 0xfffffff
int map[10][10] ;
int num[10][10] ;     //记录到(x, y)所剩的时间
int r, c, tcase ;
int sx, sy, dx, dy ;
int direct[4][2] = {1, 0, 0, -1, -1, 0, 0, 1} ;
bool flag ;

struct Node
{
    int x ;
    int y ;
    int T ;   //剩余时间
    int step ; //已走步数或者已用时间
}n, m ;

int main()
{
    int i, j ;
    cin >> tcase ;
    while (tcase --)
    {
        cin >> r >> c ;
        for (i = 1; i <= r; i ++)
            for (j = 1; j <= c; j ++)
            {
                cin >> map[i][j] ;
                if (map[i][j] == 2)
                    sx = i, sy = j ;
                if (map[i][j] == 3)
                    dx = i, dy = j ;
                num[i][j] = 0 ;         //初始化所剩时间为0
            }

        flag = false ;

        n.x = sx ;
        n.y = sy ;
        n.T = 6 ;
        n.step = 0 ;
        num[n.x][n.y] = 6 ;             // 起点的时间为6

        queue <Node> Q ;
        Q.push (n) ;
        while (! Q.empty())
        {
            m = Q.front() ;
            Q.pop () ;

            if (m.x == dx && m.y == dy && m.T > 0)
            {
                flag = true ;
                break ;
            }
            if (m.T <= 0)
            continue ;

            if (map[m.x][m.y] == 4)     //碰到Reset Time
                {
                    m.T = 6 ;
                    num[m.x][m.y] = 6 ;
                }

            for (i = 0; i < 4; i ++)
            {
                n.x = m.x + direct[i][0] ;
                n.y = m.y + direct[i][1] ;
                n.T = m.T - 1 ;
                n.step = m.step + 1;

                if (n.x > 0 && n.y > 0 && n.x <= r && n.y <= c && map[n.x][n.y] != 0 && n.T > 0)
                {

                    if (n.T <= num[n.x][n.y]) //如果当前所用时间比原来时间断,不入队列
                    continue ;
                    num[n.x][n.y] = n.T ;
                    Q.push (n) ;
                }
            }
        }
        if (flag)
            printf ("%d\n", m.step) ;
        else
            printf ("-1\n") ;
    }
    return 0 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值