#include <bits/stdc++.h>
using namespace std;
double eps = 1e-9;
const int INF = 1e9;
const int MAXN = int(5e5 + 7);
int n, m, x, y, d[3][1007][1007], dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1},
                                  ans = INF;
char c[1007][1007];
set<pair<int, pair<int, int> > > q;
inline void bfs(char c1, int id) {
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (c[i][j] == c1) {
        d[id][i][j] = 0;
        q.insert(make_pair(0, make_pair(i, j)));
      } else
        d[id][i][j] = INF;
  while (!q.empty()) {
    x = q.begin()->second.first;
    y = q.begin()->second.second;
    q.erase(q.begin());
    for (int i = 0; i < 4; i++) {
      int tox = x + dx[i], toy = y + dy[i];
      if (tox > 0 && toy > 0 && tox <= n && toy <= m && c[tox][toy] != '#') {
        int w = 0;
        if (c[tox][toy] == '.') w = 1;
        if (d[id][tox][toy] > d[id][x][y] + w) {
          q.erase(make_pair(d[id][tox][toy], make_pair(tox, toy)));
          d[id][tox][toy] = d[id][x][y] + w;
          q.insert(make_pair(d[id][tox][toy], make_pair(tox, toy)));
        }
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> c[i][j];
  for (int i = 1; i <= 3; i++) bfs('0' + i, i - 1);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (c[i][j] != '#') {
        if (d[0][i][j] != INF && d[1][i][j] != INF && d[2][i][j] != INF) {
          int cur = d[0][i][j] + d[1][i][j] + d[2][i][j];
          if (c[i][j] == '.') cur -= 2;
          ans = min(ans, cur);
        }
      }
  if (ans > INF / 2)
    cout << -1;
  else
    cout << ans;
  return 0;
}
