#include <bits/stdc++.h>
using namespace std;
const int N = 20;
const int M = 2001;
const int INF = 1e9;
const int X[] = {-1, 0, 1, 0};
const int Y[] = {0, 1, 0, -1};
int n, t, caps;
char scy[N][N];
char cap[N][N];
int r_dist[N][N];
int s_dist[N][N];
int c_id[N][N][10];
int s_id[N][N][10];
vector<int> graph[M];
bool valid(int i, int j) {
  if (i < 0 or j < 0 or i >= n or j >= n) return false;
  return isdigit(scy[i][j]);
}
void bfs(int si, int sj, int dist[N][N], bool flag) {
  queue<pair<int, int> > q;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) dist[i][j] = INF;
  dist[si][sj] = 0;
  q.push({si, sj});
  while (!q.empty()) {
    int i = q.front().first;
    int j = q.front().second;
    q.pop();
    for (int dir = 0; dir < 4; dir++) {
      int x = i + X[dir], y = j + Y[dir];
      if (!valid(x, y)) continue;
      if (dist[x][y] > dist[i][j] + 1) {
        dist[x][y] = dist[i][j] + 1;
        if (flag or dist[x][y] < r_dist[x][y]) q.push({x, y});
      }
    }
  }
}
void build_graph(int x, int y) {
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      if (isdigit(cap[i][j]) and s_dist[i][j] <= min(t, r_dist[i][j]))
        for (int k = 0; k < (scy[x][y] - '0'); k++)
          for (int l = 0; l < (cap[i][j] - '0'); l++)
            graph[s_id[x][y][k]].push_back(c_id[i][j][l]);
}
int match[M];
bool mark[M];
int augment(int u) {
  if (mark[u]) return 0;
  mark[u] = true;
  for (int v : graph[u])
    if (match[v] == -1 or augment(match[v])) {
      match[v] = u;
      return 1;
    }
  return 0;
}
int main() {
  int scys = 0;
  scanf("%d %d", &n, &t);
  for (int i = 0; i < n; i++) {
    scanf("%s", scy[i]);
    for (int j = 0; j < n; j++)
      if (isdigit(scy[i][j]))
        for (int k = 0; k < (scy[i][j] - '0'); k++) s_id[i][j][k] = scys++;
  }
  int caps = scys;
  for (int i = 0; i < n; i++) {
    scanf("%s", cap[i]);
    for (int j = 0; j < n; j++) {
      if (isdigit(cap[i][j]))
        for (int k = 0; k < (cap[i][j] - '0'); k++) c_id[i][j][k] = caps++;
      if (cap[i][j] == 'Z') bfs(i, j, r_dist, true);
    }
  }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      if (isdigit(scy[i][j])) {
        bfs(i, j, s_dist, false);
        build_graph(i, j);
      }
  int ans = 0;
  memset(match, -1, sizeof match);
  for (int i = 0; i < scys; i++) {
    memset(mark, false, sizeof mark);
    ans += augment(i);
  }
  printf("%d\n", ans);
  return 0;
}
