#include <bits/stdc++.h>
using namespace std;
const int INF = 6e8;
const int maxn = 1005;
int dp[5][maxn][maxn];
char g[maxn][maxn];
int n, m;
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
void bfs(char ch) {
  queue<pair<int, int> > q;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (g[i][j] == ch) {
        q.push(make_pair(i, j));
        dp[ch - '0'][i][j] = 0;
      }
    }
  }
  while (!q.empty()) {
    pair<int, int> u = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int xx = u.first + dir[i][0];
      int yy = u.second + dir[i][1];
      if (g[xx][yy] == '#' || xx < 1 || xx > n || yy < 1 || yy > m) continue;
      if (dp[ch - '0'][xx][yy] >
          dp[ch - '0'][u.first][u.second] + (g[u.first][u.second] == '.')) {
        dp[ch - '0'][xx][yy] =
            dp[ch - '0'][u.first][u.second] + (g[u.first][u.second] == '.');
        q.push(make_pair(xx, yy));
      }
    }
  }
}
void solve() {
  char a = '1', b = '2', c = '3';
  bfs(a);
  bfs(b);
  bfs(c);
  int res = INF;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      res =
          min(res, dp[1][i][j] + dp[2][i][j] + dp[3][i][j] + (g[i][j] == '.'));
    }
  }
  if (res == INF)
    puts("-1");
  else
    printf("%d\n", res);
}
int main() {
  while (scanf("%d %d", &n, &m) != EOF) {
    for (int i = 1; i <= n; i++) {
      scanf("%s", g[i] + 1);
      for (int j = 1; j <= m; j++)
        dp[1][i][j] = dp[2][i][j] = dp[3][i][j] = INF;
    }
    solve();
  }
  return 0;
}
