#include <bits/stdc++.h>
using namespace std;
int n, m, dist[4][4], d[4][1005][1005], vis[1005][1005];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
string arr[1005];
vector<pair<int, int> > v[4];
queue<pair<int, int> > q;
int isvalid(int x, int y, int n, int m) {
  if (x >= 0 && x < n && y >= 0 && y < m) return 1;
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> arr[i];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (arr[i][j] != '#' && arr[i][j] != '.')
        v[arr[i][j] - '1'].push_back(make_pair(i, j));
  for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++)
      if (i != j) dist[i][j] = 10000000;
  int ans = 10000000;
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < n; j++)
      for (int k = 0; k < m; k++) {
        vis[j][k] = 0;
        d[i][j][k] = 10000000;
      }
    for (int j = 0; j < v[i].size(); j++) {
      q.push(v[i][j]);
      vis[v[i][j].first][v[i][j].second] = 1;
      d[i][v[i][j].first][v[i][j].second] = 0;
    }
    while (!q.empty()) {
      pair<int, int> t = q.front();
      q.pop();
      int x = 0, y = 0;
      for (int j = 0; j < 4; j++) {
        x = t.first + dx[j];
        y = t.second + dy[j];
        if (isvalid(x, y, n, m) && arr[x][y] != '#') {
          if (!vis[x][y]) {
            vis[x][y] = 1;
            d[i][x][y] = d[i][t.first][t.second] + 1;
            if (arr[x][y] != '.' && arr[x][y] != '#') {
              int idx = arr[x][y] - '1';
              if (idx != i)
                dist[idx][i] = dist[i][idx] = min(dist[idx][i], d[i][x][y]);
            }
            q.push(make_pair(x, y));
          }
        }
      }
    }
  }
  for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++)
      for (int k = 0; k < 3; k++)
        if (i != j && k != j && i != k)
          ans = min(ans, dist[i][j] + dist[j][k] - 2);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int temp = 0;
      if (arr[i][j] != '.') continue;
      for (int k = 0; k < 3; k++) temp += (d[k][i][j] - 1);
      ans = min(ans, temp + 1);
    }
  if (ans >= 1000000)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
