#include <bits/stdc++.h>
using namespace std;
const long long N = 1e3 + 100, inf = 1e15;
long long dis[N][N][6], clr[6][6], ans = inf;
queue<pair<int, int> > q[3];
char a[N][N];
bool mark[N][N][6];
pair<int, int> k;
int ki, kj, n, m, x, y;
int xx[] = {0, 1, 0, -1}, yy[] = {1, 0, -1, 0};
bool is_vallid(int x, int y) {
  if (x >= 0 && x < n && y >= 0 && y < m) return 1;
  return 0;
}
void init() {
  for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++) clr[i][j] = inf;
  for (int i = 0; i < N; i++)
    for (int j = 0; j < N; j++)
      for (int c = 0; c < 4; c++) dis[i][j][c] = inf;
}
void bfs(int b) {
  while (!q[b].empty()) {
    k = q[b].front();
    ki = k.first, kj = k.second;
    if (a[ki][kj] - '1' != b && a[ki][kj] != '#' && a[ki][kj] != '.')
      clr[b][a[ki][kj] - '1'] = min(dis[ki][kj][b], clr[b][a[ki][kj] - '1']);
    for (int i = 0; i < 4; i++) {
      x = ki + xx[i], y = kj + yy[i];
      if (is_vallid(x, y) && a[x][y] != '#' && !mark[x][y][b]) {
        q[b].push({x, y});
        dis[x][y][b] = dis[ki][kj][b] + 1;
        mark[x][y][b] = 1;
      }
    }
    q[b].pop();
  }
}
int main() {
  init();
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
      if (a[i][j] != '.' && a[i][j] != '#') {
        q[a[i][j] - '1'].push({i, j});
        mark[i][j][a[i][j] - '1'] = 1;
        dis[i][j][a[i][j] - '1'] = 0;
      }
    }
  for (int i = 0; i < 3; i++) bfs(i);
  ans = min(min(clr[0][1] + clr[0][2], clr[1][0] + clr[1][2]),
            clr[2][0] + clr[2][1]);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      ans = min(ans, dis[i][j][0] + dis[i][j][1] + dis[i][j][2]);
  if (ans >= inf) {
    cout << -1;
    return 0;
  }
  cout << ans - 2;
}
