#include<iostream>
#include<queue>
#include<cstring>
#include<cmath>
using namespace std;
const int N = 2501;
int n,m,_map[N][N],sx,sy,book[N][N],cnt,r=1e-6,vis[N][N],l,mid,ans;
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int bfs(int d){
queue <int> x,y;
memset(vis,0,sizeof(vis));
vis[sx][sy]=1;
x.push(sx);
y.push(sy);
int tmp=1;
while(!x.empty())
{
int xx = x.front();
int yy = y.front();
x.pop(),y.pop();
for(int i=0;i<4;i++)
{
int tx = xx + dir[i][0];
int ty = yy + dir[i][1];
if(tx>=1 && tx<=n && ty>=1 && ty<=m && vis[tx][ty]==0)
{
int sum = abs(_map[tx][ty]-_map[xx][yy]);
if(sum >= d) continue;
else
{
if(book[tx][ty]) tmp++;
x.push(tx),y.push(ty);
vis[tx][ty] = 1;
}
}
}
}
if(tmp<=cnt)
return 1;
else
return 0;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&_map[i][j]);
r = max(r,_map[i][j]);
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&book[i][j]);
if(book[i][j]){
cnt++;//记录标点数
}
if(cnt==1){
int sx = i;
int sy = j;
}
}
}
int pos=0;
for(int i=28;i>=0;i--)
if(bfs(pos+(1<<i))) pos+=1<<i;
cout<<++pos;
return 0;
}
求助!!