import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int n,m;
static int high[][] = new int[510][510];
static int flag[][] = new int[510][510];
static int st[][] = new int[510][510];
static int x1 = 0,y1 = 0;
static int cnt_flag = 0;
static Queue<PII> queue;
static int dx[] = {-1,0,1,0};
static int dy[] = {0,1,0,-1};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
high[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
flag[i][j] = scanner.nextInt();
if (flag[i][j] == 1) {
cnt_flag ++;
x1 = i;y1 = j;
}
}
}
int l = -1,r = Integer.MAX_VALUE;
while (l + 1 < r) {
int mid = (l + r) / 2;
if (check(mid)) {
r = mid;
} else {
l = mid;
}
}
System.out.println(r);
}
public static boolean check(int mid) {
int count = 1;
queue = new LinkedList<>();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
st[i][j] = 0;
}
}
queue.offer(new PII(x1,y1));
st[x1][y1] = 1;
while (!queue.isEmpty()) {
PII t = queue.poll();
for (int i = 0; i < 4; i++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 1 || a > n || b < 1 || b > m) continue;
if (st[a][b] == 1) continue;
if (Math.abs(high[t.x][t.y] - high[a][b]) > mid) continue;
st[a][b] = 1;
queue.offer(new PII(a,b));
if (flag[a][b] == 1) {
count ++;
if (cnt_flag == count) {
return true;
}
}
}
}
return false;
}
}
class PII {
int x;
int y;
public PII(int x, int y) {
this.x = x;
this.y = y;
}
}