#include <bits/stdc++.h>
#define speed ios::sync_with_stdio(0);cin.tie(0)
using namespace std;
int main(){
speed;
int n, m, x, y;
cin >> n >> m;
int t[n][m]; int f[n][m]; int c[n][m];
for(int i=0; i<n; i++) for(int j=0; j<m; j++){
cin >> t[i][j];
c[i][j] = 0;
if(t[i][j]==-1){x=i; y=j;}
}
for(int i=0; i<n; i++) for(int j=0; j<m; j++) cin >> f[i][j];
long long int temp=0;
int e=0;
int old=0; int r=0;
while(true){
for(int i=0; i<n+m; i++){
for(int j=-i; j<i+1; j++){
int dx1=x+i-abs(j);
int dx2=x-i+abs(j);
int dy=y+j;
if((dx1>-1&&dx1<n&&dy>-1&&dy<m)&&(t[dx1][dy]==-1 || t[dx1][dy] >= temp)&&((t[dx1][dy]==-1)||(dx1-1>-1&&c[dx1-1][dy])||(dx1+1<n&&c[dx1+1][dy])||(dy-1>-1&&c[dx1][dy-1])||(dy+1<m&&c[dx1][dy+1]))) c[dx1][dy]=1;
if((dx2>-1&&dx2<n&&dy>-1&&dy<m)&&(t[dx2][dy]==-1 || t[dx2][dy] >= temp)&&((t[dx2][dy]==-1)||(dx2-1>-1&&c[dx2-1][dy])||(dx2+1<n&&c[dx2+1][dy])||(dy-1>-1&&c[dx2][dy-1])||(dy+1<m&&c[dx2][dy+1]))) c[dx2][dy]=1;
}
}
if(old==e) r++;
else r=0;
if(r==e){temp--; break;}
old=e; e=0;
for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(c[i][j]){
e+=f[i][j];
c[i][j]=0;
}
if(old==e&&temp>0&&e-1==1) break;
if(e==0) break;
temp++;
}
cout << temp;
}