#include <bits/stdc++.h>
using namespace std;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, -1, 1};
int n, m;
char s[1005][1005];
int d[4][1002][1002];
bool isvalid(int x, int y) { return (x >= 0 and x < n and y >= 0 and y < m); }
void bfs(int x) {
  deque<pair<int, int> > Q;
  for (int(i) = 0; (i) < (n); (i)++)
    for (int(j) = 0; (j) < (m); (j)++)
      if (s[i][j] - '0' == x)
        Q.push_back({i, j}), d[x][i][j] = 0;
      else
        d[x][i][j] = 1e8;
  while (!Q.empty()) {
    pair<int, int> ele = Q.front();
    Q.pop_front();
    for (int(i) = 0; (i) < (4); (i)++)
      if (isvalid(ele.first + dx[i], ele.second + dy[i])) {
        if (s[ele.first + dx[i]][ele.second + dy[i]] == '#') continue;
        int exp = d[x][ele.first][ele.second] +
                  (s[ele.first + dx[i]][ele.second + dy[i]] == '.' ? 1 : 0);
        if (exp < d[x][ele.first + dx[i]][ele.second + dy[i]]) {
          if (exp == d[x][ele.first][ele.second])
            Q.push_front({ele.first + dx[i], ele.second + dy[i]});
          else
            Q.push_back({ele.first + dx[i], ele.second + dy[i]});
          d[x][ele.first + dx[i]][ele.second + dy[i]] = exp;
        }
      }
  }
}
int main() {
  scanf("%d", &n);
  scanf("%d", &m);
  for (int(i) = 0; (i) < (n); (i)++) scanf("%s", s[i]);
  for (int(i) = (1); (i) <= (3); (i)++) bfs(i);
  int ans = 1e8;
  for (int(i) = 0; (i) < (n); (i)++)
    for (int(j) = 0; (j) < (m); (j)++) {
      int cost = d[1][i][j] + d[2][i][j] + d[3][i][j];
      if (s[i][j] == '.') cost -= 2;
      ans = min(ans, cost);
    }
  if (ans < 1e8)
    printf("%d\n", ans);
  else
    printf("%d\n", -1);
  return 0;
}
