Nightmare HDU - 1072 (BFS)

#include <stdio.h>
#include <cstring>
#include <queue>

using namespace std;

struct Node
{
    int x, y, time, ans;
};

queue<Node> q;

int map[9][9];
bool mark[9][9];
int n, m;
int sx, sy;
int dir[][2] = {1,0, -1,0, 0,1, 0,-1};

int BFS()
{
    Node start;
    start.x = sx, start.y = sy, start.time = 6, start.ans = 0;
    mark[sx][sy] = true;
    q.push(start);
    
    int nx, ny;
    while(!q.empty())
    {
        Node cur = q.front();
        q.pop();
        if(map[cur.x][cur.y] == 3)
            return cur.ans;
        
        for(int i = 0; i < 4; i++)
        {
            nx = cur.x + dir[i][0];
            ny = cur.y + dir[i][1];
            if(nx < 0 || ny < 0 || nx >= n || ny >= m)
                continue;
            if(map[nx][ny] == 0)
                 continue;
            Node tmp;
            tmp.x = nx, tmp.y = ny, tmp.time = cur.time - 1, tmp.ans = cur.ans + 1;
            if(tmp.time < 1)
                continue;
            
            if(map[nx][ny] == 4)
            {
                tmp.time = 6;
                map[nx][ny] = 0;       //重置器应该是只使用一次就应该会达到最优解,所以使用一次后,就标记为不可使用 
            }
            q.push(tmp);
        }
    }
    return -1;
}

int main()
{
    int c;
    scanf("%d", &c);
    while(c--)
    {
        scanf("%d%d", &n, &m);
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
            {
                scanf("%d", &map[i][j]);
                if(map[i][j] == 2)
                    sx = i, sy = j;
            }
        memset(mark, 0, sizeof(mark));
        while(!q.empty())
            q.pop();
        int res = BFS();
        printf("%d\n", res);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值