#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
char s[maxn][maxn];
int dis[3][maxn][maxn];
int n, m;
bool vis[maxn][maxn];
vector<pair<int, int> > v[3];
int ans = maxn * maxn;
void Bfs(int id) {
  int id1 = (id + 1) % 3, id2 = (id + 2) % 3, did[3] = {-1, -1, -1};
  memset(vis, false, sizeof(vis));
  queue<pair<int, int> > q;
  int sz = v[id].size();
  for (int i = 0; i <= sz - 1; i++) {
    vis[v[id][i].first][v[id][i].second] = true;
    dis[id][v[id][i].first][v[id][i].second] = 0;
    q.push(v[id][i]);
  }
  int d = 0;
  pair<int, int> now;
  while (!q.empty()) {
    int t = q.size();
    while (t--) {
      now = q.front();
      q.pop();
      for (int i = 0; i <= 3; i++) {
        int tx = now.first + dx[i], ty = now.second + dy[i];
        if (tx < 0 || tx >= n || ty < 0 || ty >= m || vis[tx][ty] ||
            s[tx][ty] == '#')
          continue;
        if (s[tx][ty] == '.')
          vis[tx][ty] = true, dis[id][tx][ty] = d + 1,
          q.push(make_pair(tx, ty));
        else {
          if (s[tx][ty] - '1' != id) {
            if (did[s[tx][ty] - '1'] == -1) did[s[tx][ty] - '1'] = d;
            dis[id][tx][ty] = d + 1, vis[tx][ty] = true,
            q.push(make_pair(tx, ty));
          }
        }
      }
    }
    d++;
  }
  if (did[id1] != -1 && did[id2] != -1) ans = min(ans, did[id1] + did[id2]);
}
void Solve() {
  for (int i = 0; i <= n - 1; i++)
    for (int j = 0; j <= m - 1; j++)
      if (s[i][j] == '.' && dis[0][i][j] != -1 && dis[1][i][j] != -1 &&
          dis[2][i][j] != -1) {
        ans = min(ans, dis[0][i][j] + dis[1][i][j] + dis[2][i][j] - 2);
      }
  if (ans == maxn * maxn)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
bool Check(int x, int y) {
  int c1 = 0, c2 = 0, c3 = 0;
  for (int i = 0; i <= 3; i++) {
    int tx = x + dx[i], ty = y + dy[i];
    if (tx < 0 || tx >= n || ty < 0 || ty >= m) {
      c3++;
      continue;
    }
    if (s[x][y] == s[tx][ty]) c1++;
    if (s[tx][ty] == '#') c2++;
  }
  return c1 + c2 + c3 != 4;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i <= n - 1; i++) scanf("%s", s[i]);
  for (int i = 0; i <= n - 1; i++)
    for (int j = 0; j <= m - 1; j++) {
      if (s[i][j] == '1' || s[i][j] == '2' || s[i][j] == '3') {
        if (Check(i, j)) v[s[i][j] - '1'].push_back(make_pair(i, j));
      }
    }
  memset(dis, -1, sizeof(dis));
  Bfs(0), Bfs(1), Bfs(2);
  Solve();
  return 0;
}
