UVA 11573 - Ocean Currents【BFS+优先队列】

题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2620

题意:给定一个海面,数字分别代表海流方向,顺着海流不用费能量,逆海流要费1点能量,每次询问给一个起点一个终点,问起点到终点耗费的最小能量

思路:广搜,队列用优先队列,每次取能量最低的点。

代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
#include <math.h>
#include <map>
#include <string>

using namespace std;

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

int r, c;
char p[1010][1010];
int vis[1010][1010];
int x1, y11, x2, y2;

bool is_ok(int x, int y)
{
    if (x >= 1 && x <= r && y >= 1 && y <= c) return true;
    return false;
}

struct node
{
    int x, y;
    int t;
    node() {}
    friend bool operator < (node a,node b) 
    {
        return a.t > b.t;
    }
};

int main()
{
    while (scanf("%d%d",&r,&c) != EOF)
    {
        for (int i = 1; i <= r; i++)
            scanf("%s", p[i] + 1);

        int n;
        cin >> n;
        while(n--)
        {
            int ans = 0;
            cin >> x1 >> y11 >> x2 >> y2;
            priority_queue<node> que;
            while (!que.empty()) que.pop();
            memset(vis, -1, sizeof(vis));

            vis[x1][y11] = 0;
            node a;
            a.x = x1, a.y = y11, a.t = 0;
            que.push(a);

            while (!que.empty())
            {
                node tmp = que.top(); que.pop();
                if (tmp.x == x2 && tmp.y == y2)
                {
                    ans = tmp.t;
                    break;
                }
                node res;
                for (int i = 0; i < 8; i++)
                {
                    int x = tmp.x + dir[i][0];
                    int y = tmp.y + dir[i][1];
                    if (!is_ok(x, y)) continue;
                    //if (!is_ok(x, y) && vis[x][y] != -1) continue;
                    res.x = x; res.y = y; 
                    if (p[tmp.x][tmp.y]-'0' == i) res.t = tmp.t;
                    else  res.t = tmp.t + 1;

                    if (vis[x][y] == -1 || res.t < vis[x][y])
                    {
                        vis[x][y] = res.t;
                        que.push(res);
                    }
                }
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值