传送门
分析
我们去二分最后的答案,然后枚举一个最小值,判断这个图能否走通即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 110;
const ll mod= 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a){char c=getchar();T x=0,f=1;while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+c-'0';c=getchar();}a=f*x;}
int gcd(int a,int b){return (b>0)?gcd(b,a%b):a;}
int g[N][N];
int n;
bool st[N][N];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
bool check(int l,int r){
memset(st,0,sizeof st);
queue<PII> q;
q.push({1,1});
st[1][1] = 1;
while(q.size()){
auto t = q.front();
q.pop();
if(t.fi + t.se == 2 * n) return true;
for(int i = 0;i < 4;i++){
int xx = t.fi + dx[i];
int yy = t.se + dy[i];
if(xx < 1 || xx > n || yy < 1 || yy > n) continue;
if(st[xx][yy] || g[xx][yy] < l || g[xx][yy] > r) continue;
st[xx][yy] = 1;
q.push({xx,yy});
}
}
return false;
}
int main(){
read(n);
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
read(g[i][j]);
int l = 0,r = 3000;
int ans = INF;
while(l < r){
int mid = l + r >> 1;
bool flag = 0;
for(int i = 0;i <= 3000 - mid;i++){
if(g[1][1] < i || g[1][1] > i + mid) continue;
if(check(i,i + mid)){
flag = 1;
break;
}
}
if(flag){
ans = mid;
r = mid;
}
else l = mid + 1;
}
di(ans);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/