1562: PUBG(dijkstra算法)

1562: PUBG
时间限制: 1 Sec 内存限制: 128 MB
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
就是求单源最短路,迪杰斯特拉算法

#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const int maxn = 1e2 + 10;
int d[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};
int sx, sy, ex, ey, n;
int ans = -1;
struct node
{
    int x, y, c;
    bool operator < (const node &r) const
    {
        return c > r.c;
    }
};
bool vis[maxn][maxn];
int dist[maxn][maxn];
int m[maxn][maxn];
void dijkstra()
{
    memset(vis, false, sizeof(vis));
    memset(dist, 0x3f, sizeof(dist));
    dist[sx][sy] = 0;
    priority_queue<node> q;
    q.push(node{sx, sy, 0});
    while(!q.empty())
    {
        node tmp = q.top();
        q.pop();
        vis[tmp.x][tmp.y] = true;
        for(int i = 0; i < 4; ++i)
        {
            int x = tmp.x + d[i][0];
            int y = tmp.y + d[i][1];
            if(x == ex && y == ey)
            {
                ans = tmp.c;
                return;
            }
            if(x <= n && x >= 1 && y <= n && y >= 1 && !vis[x][y] && dist[x][y] > tmp.c + m[x][y])
            {
                dist[x][y] = tmp.c + m[x][y];
                q.push(node{x, y, dist[x][y]});
            }
        }
    }
}
 
int main()
{
    while(cin >> n)
    {
        for(int i = 1; i <= n; ++i)
        {
            for(int j = 1; j <= n; ++j)
            {
                cin >> m[i][j];
                if(m[i][j] == -1)
                    sx = i, sy = j;
                else if(m[i][j] == -2)
                    ex = i, ey = j;
            }
        }
        dijkstra();
        cout << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值