链接:https://ac.nowcoder.com/acm/problem/15752
最近,喜爱ACM的PBY同学沉迷吃鸡,无法自拔,于是又来到了熟悉的ERANGEL。经过一番搜寻,PBY同学准备动身前往安全区,但是,地图中埋伏了许多LYB,PBY的枪法很差,希望你能够帮他找到一条路线,每次只能向上、下、左、右移动,尽可能遇到较少的敌人。
输入描述:
题目包含多组测试,请处理到文件结束; 第一行是一个整数n,代表地图的大小; 接下来的n行中,每行包含n个整数a,每个数字a代表当前位置敌人的数量; 1 < n <= 100,1 <= a <= 100,-1代表当前位置,-2代表安全区。
输出描述:
对于每组测试数据,请输出从当前位置到安全区所遇到最少的敌人数量,每个输出占一行。
示例1
输入
5 6 6 0 -2 3 4 2 1 2 1 2 2 8 9 7 8 1 2 1 -1 9 7 2 1 2
输出
9
思路:刚开始是用BFS来做的,后来听说最短路效率比较高,所以跑了一遍Dijkstra。
#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;
}