1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=110,move[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; int m[N][N],n,ans=0; bool visit[N][N]; template<typename T>inline void read(T &x) { char ch=getchar(); T f=1; x=0; while(!('0'<=ch&&ch<='9')) { if(ch=='-') f=-1; ch=getchar(); } do { x=(x<<3)+(x<<1)+ch-48; ch=getchar(); }while('0'<=ch&&ch<='9'); x*=f; } void dfs(int x,int y,const int& sml,const int& big) { if(visit[x][y]) return; visit[x][y]=true; for(int i=0;i<4;i++) { int nx=x+move[i][0],ny=y+move[i][1]; if(nx<1||nx>n||ny<1||ny>n) continue; if(m[nx][ny]<sml||m[nx][ny]>big) continue; dfs(nx,ny,sml,big); } } inline bool check(int x) { for(int i=max(0,max(m[1][1],m[n][n])-x);i<=min(110-x,min(m[1][1],m[n][n]));i++) { memset(visit,0,sizeof(visit)); dfs(1,1,i,x+i); if(visit[n][n]) return true; } return false; } int main() { read(n); for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) read(m[i][j]); int l=0,r=N; while(l<=r) { int mid=l+r>>1; if(check(mid)) { ans=mid; r=mid-1; } else l=mid+1; } printf("%d",ans); return 0; }
|