#include <bits/stdc++.h>
using namespace std;
const int INF = (1 << 30);
int N, M, S[1000][1000], dis[3][1000000], RES[1000000];
const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
void BFS(int f) {
  queue<int> q;
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++) {
      dis[f][i * M + j] = INF;
      if (S[i][j] == f) {
        dis[f][i * M + j] = 0;
        q.push(i * M + j);
      }
    }
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    int x = u / M, y = u % M;
    for (int i = 0; i < 4; i++) {
      int tx = x + d[i][0], ty = y + d[i][1];
      if (tx < 0 || ty < 0 || tx >= N || ty >= M) continue;
      if (S[tx][ty] == 4) continue;
      if (dis[f][u] + 1 < dis[f][tx * M + ty]) {
        dis[f][tx * M + ty] = dis[f][u] + 1;
        q.push(tx * M + ty);
      }
    }
  }
}
void solve(int f, int ff) {
  int ans = INF;
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++)
      if (S[i][j] == f) ans = min(ans, dis[ff][i * M + j]);
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++)
      if (S[i][j] == f) dis[ff][i * M + j] = ans;
}
int main() {
  scanf("%d%d", &N, &M);
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++) {
      char c;
      do {
        scanf("%c", &c);
      } while (c != '#' && c != '.' && c != '1' && c != '2' && c != '3');
      switch (c) {
        case '1':
          S[i][j] = 0;
          break;
        case '2':
          S[i][j] = 1;
          break;
        case '3':
          S[i][j] = 2;
          break;
        case '.':
          S[i][j] = 3;
          break;
        case '#':
          S[i][j] = 4;
          break;
      }
    }
  for (int i = 0; i < 3; i++) BFS(i);
  for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++) solve(i, j);
  for (int i = 0; i < N * M; i++)
    for (int k = 0; k < 3; k++) {
      if (dis[k][i] == INF) {
        RES[i] = INF;
        break;
      }
      RES[i] += dis[k][i];
    }
  int ans = INF;
  for (int i = 0; i < N * M; i++) ans = min(ans, RES[i]);
  if (ans == INF)
    puts("-1");
  else
    printf("%d\n", ans - 2);
}
