#include <bits/stdc++.h>
using namespace std;
static const int N = 1005;
static const int inf = 1000005;
int n, m, lx, ly, cntt = 0, cnttt = 0, flag = 0, dis[4][1005][1005];
int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};
bool vis1[N][N];
char mp[N][N];
queue<int> qx;
queue<int> qy;
void init() {
  for (int k = 1; k <= 3; ++k)
    for (int i = 1; i <= n; ++i)
      for (int j = 1; j <= m; ++j) dis[k][i][j] = inf;
}
void bfs() {
  for (; !qx.empty();) {
    int tmpx = qx.front();
    int tmpy = qy.front();
    qx.pop();
    qy.pop();
    for (int i = 0; i < 4; ++i) {
      int tx = tmpx + dx[i];
      int ty = tmpy + dy[i];
      if (tx < 1 || ty < 1 || tx > n || ty > m) continue;
      if (mp[tx][ty] == '.' && dis[flag][tmpx][tmpy] + 1 < dis[flag][tx][ty])
        dis[flag][tx][ty] = dis[flag][tmpx][tmpy] + 1, qx.push(tx), qy.push(ty);
      else if (mp[tx][ty] == '*' && dis[flag][tmpx][tmpy] < dis[flag][tx][ty])
        dis[flag][tx][ty] = dis[flag][tmpx][tmpy], qx.push(tx), qy.push(ty);
    }
  }
}
void dfs(int x, int y) {
  if (mp[x][y] != '*' || x < 1 || y < 1 || x > n || y > m || vis1[x][y]) return;
  ++cnttt;
  vis1[x][y] = 1;
  dis[flag][x][y] = 0;
  qx.push(x);
  qy.push(y);
  for (int i = 0; i < 4; ++i) {
    int tx = x + dx[i];
    int ty = y + dy[i];
    dfs(tx, ty);
  }
}
int main() {
  scanf("%d%d", &n, &m);
  init();
  for (int i = 1; i <= n; ++i) scanf("%s", mp[i] + 1);
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (mp[i][j] == '1' || mp[i][j] == '2' || mp[i][j] == '3')
        mp[i][j] = '*', ++cntt;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      if (mp[i][j] == '*' && !vis1[i][j]) {
        ++flag;
        dfs(i, j);
        if (flag == 1 && cntt == cnttt) {
          printf("0");
          return 0;
        }
        bfs();
      }
    }
  int ans = inf;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      if (mp[i][j] != '#') {
        int kk = 0;
        for (int k = 1; k <= flag; ++k) {
          kk += dis[k][i][j];
          if (mp[i][j] == '.') --kk;
        }
        ans = min(ans, kk + 1);
      }
    }
  if (ans >= inf)
    puts("-1");
  else
    printf("%d", ans);
  return 0;
}
