如果使用bfs则需要注意每个点都可能被重复更新
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <cstdio>
#include <iomanip>
#include <string>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#include <unordered_map>
#include <sstream>
#include <unordered_set>
const int inf = 0x3f3f3f3f;
const double pi = 4 * atan(1);
#define de(x) cerr<<#x<<"="<<x<<'\n'
#define dde(x,y) cerr<<#x<<'='<<x<<","<<#y<<"="<<y<<'\n'
typedef long long ll;
using namespace std;
typedef pair<int, int>PII;
typedef pair<ll, pair<int, int>>PIII;
//第一个存距离,后面两个存点的坐标x,y
const int N = 510;
ll dist[N][N],maxv, n, g[N][N];
struct nod {
int x, y;
}ed;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
void bfs() {
dist[0][0] = 0;
priority_queue<PIII, vector<PIII>, greater<PIII>>heap;
//按首个元素从小到大排序,每次出队都是最小的
heap.push({ 0,{0,0} });
while (heap.size()) {
PIII t = heap.top(); heap.pop();
int distance = t.first, tx = t.second.first, ty = t.second.second;
for (int i = 0; i < 4; i++) {
int x = tx + dx[i], y = ty + dy[i];
if (x < 0 || y < 0 || x >= n || y >= n)continue;
ll d = (g[tx][ty] - g[x][y]) * (g[tx][ty] - g[x][y]);
//原来的点到新点的距离
if (dist[x][y] > dist[tx][ty] + d) {
//这题中每个点不止会更新一次,当点的距离更小的时候把这个点重新入队更新其他点
dist[x][y] = dist[tx][ty] + d;
heap.push({ dist[x][y] ,{x,y} });
}
}
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> g[i][j];
dist[i][j] = inf;//初始化
if (g[i][j] > maxv) {//找最大的山顶
maxv = g[i][j];
ed = { i,j };
}
}
}
bfs();
cout << dist[ed.x][ed.y] << endl;
}