#include <bits/stdc++.h>
using namespace std;
char s[1010][1010];
queue<pair<int, int> > q[3];
int dist[3][1010][1010];
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int n, m;
void BFS(int idx) {
  while (!q[idx].empty()) {
    pair<int, int> cords = q[idx].front();
    q[idx].pop();
    for (int i = 0; i < 4; i++) {
      int x = cords.first + dx[i];
      int y = cords.second + dy[i];
      if (x >= 0 && y >= 0 && x < n && y < m && s[x][y] != '#')
        if (dist[idx][x][y] == -1 ||
            dist[idx][x][y] > dist[idx][cords.first][cords.second] +
                                  (s[x][y] == '.' ? 1 : 0)) {
          dist[idx][x][y] =
              dist[idx][cords.first][cords.second] + (s[x][y] == '.' ? 1 : 0);
          q[idx].push(make_pair(x, y));
        }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", s[i]);
  memset(dist, -1, sizeof dist);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      if (s[i][j] != '#' && s[i][j] != '.') {
        q[s[i][j] - '1'].push(make_pair(i, j));
        dist[s[i][j] - '1'][i][j] = 0;
      }
    }
  int minimum = 999999999;
  for (int i = 0; i < 3; i++) BFS(i);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      bool ok = true;
      for (int k = 0; k < 3; k++)
        if (dist[k][i][j] == -1) ok = false;
      if (s[i][j] == '.') {
        if (ok)
          minimum =
              min(minimum, dist[0][i][j] + dist[1][i][j] + dist[2][i][j] - 2);
      } else if (ok)
        minimum = min(minimum, dist[0][i][j] + dist[1][i][j] + dist[2][i][j]);
    }
  if (minimum == 999999999) minimum = -1;
  printf("%d\n", minimum);
  return 0;
}
