#include <bits/stdc++.h>
using namespace std;
int d[3][1000][1000];
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int main() {
  memset(d, -1, sizeof(d));
  int n, m, ans = -1;
  scanf("%d %d", &n, &m);
  char a[n][m];
  for (int i = 0; i < n; ++i) scanf("%s", a[i]);
  for (int i = 0; i < 3; ++i) {
    deque<pair<int, int> > q;
    for (int j = 0; j < n; ++j)
      for (int k = 0; k < m; ++k)
        if (a[j][k] - '1' == i) {
          d[i][j][k] = 0;
          q.push_back(make_pair(j, k));
        }
    while (!q.empty()) {
      int x = q.front().first, y = q.front().second;
      q.pop_front();
      for (int j = 0; j < 4; ++j) {
        int xx = x + dx[j], yy = y + dy[j];
        if (xx < 0 || yy < 0 || xx >= n || yy >= m || a[xx][yy] == '#')
          continue;
        int dis = d[i][x][y] + (a[xx][yy] == '.');
        if (d[i][xx][yy] == -1 || d[i][xx][yy] > dis) {
          d[i][xx][yy] = dis;
          if (a[xx][yy] == '.')
            q.push_back(make_pair(xx, yy));
          else
            q.push_back(make_pair(xx, yy));
        }
      }
    }
  }
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) {
      if (d[0][i][j] != -1 && d[1][i][j] != -1 && d[2][i][j] != -1) {
        if (ans == -1 ||
            ans > d[0][i][j] + d[1][i][j] + d[2][i][j] - 2 * (a[i][j] == '.'))
          ans = d[0][i][j] + d[1][i][j] + d[2][i][j] - 2 * (a[i][j] == '.');
      }
    }
  printf("%d\n", ans);
}
