#include <bits/stdc++.h>
using namespace std;
int n, m;
const int N = 1010;
const int INF = 1e9;
char M[N][N];
int dis[4][N][N], np, ans;
pair<int, int> lst[N * N];
queue<pair<int, int> > Q;
int comp(pair<int, int> a, pair<int, int> b) {
  return dis[np][a.first][a.second] < dis[np][b.first][b.second];
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) scanf("%s", M[i] + 1);
  ans = INF;
  for (int k = 1; k <= 3; ++k) {
    for (int i = 1; i <= n; ++i)
      for (int j = 1; j <= m; ++j)
        if (M[i][j] == '0' + k)
          dis[k][i][j] = 0, Q.push(make_pair(i, j));
        else
          dis[k][i][j] = INF;
    while (!Q.empty()) {
      pair<int, int> t = Q.front();
      Q.pop();
      for (int di = -1; di <= 1; ++di)
        for (int dj = -1; dj <= 1; ++dj)
          if (abs(di) + abs(dj) == 1)
            if (t.first + di >= 1 && t.first + di <= n)
              if (t.second + dj >= 1 && t.second + dj <= m)
                if (M[t.first + di][t.second + dj] != '#')
                  if (dis[k][t.first + di][t.second + dj] >
                      dis[k][t.first][t.second] +
                          (M[t.first + di][t.second + dj] == '.'))
                    dis[k][t.first + di][t.second + dj] =
                        dis[k][t.first][t.second] +
                        (M[t.first + di][t.second + dj] == '.'),
                                                    Q.push(make_pair(
                                                        t.first + di,
                                                        t.second + dj));
    }
  }
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      ans = min(ans + 0ll, 0ll + dis[1][i][j] + dis[2][i][j] + dis[3][i][j] -
                               (M[i][j] == '.') * 2);
  if (ans > n * m) ans = -1;
  printf("%d\n", ans);
}
