#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 510;
int n, m;
int high[N][N];
int flag[N][N];
int dist[N][N];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
typedef pair<int, int> PII;
queue<PII> q;
int cnt;
PII start;
bool bfs(int x, int y, int h) {
int cnt_1 = 1;
memset(dist, -1, sizeof(dist));
dist[x][y] = 0;
q.push({x, y});
while (!q.empty()) {
PII t = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int tx = t.first + dx[i], ty = t.second + dy[i];
if (tx < 1 || tx > n || ty < 1 || ty > m) continue;
if (dist[tx][ty] >= 0) continue;
if (abs(high[tx][ty] - high[t.first][t.second]) > h) continue;
dist[tx][ty] = dist[t.first][t.second] + 1;
if (flag[tx][ty] == 1)cnt_1 += 1;
q.push({tx, ty});
}
}
return false;
}
bool check(int h) {
bool res = bfs(start.first, start.second, h);
return res;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &high[i][j]);
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &flag[i][j]);
if (flag[i][j] == 1) {
cnt++;
start = {i, j};
}
}
}
int l = -1, r = 1e9 + 1;
while(l + 1 < r) {
int mid = (l + r) / 2;
if (check(mid)) r = mid;
else l = mid;
}
printf("%d\n", r);
return 0;
}