#include <bits/stdc++.h>
using namespace std;
string itos(int x) {
  stringstream ss;
  ss << x;
  return ss.str();
}
char b[1010][1010];
int n, m, dist[3][1010][1010], best[3][3], vis[1010][1010], res = 1000000007;
pair<int, int> dir[4] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    cin.ignore();
    cin >> b[i];
  }
  for (int i = 0; i < 3; i++)
    for (int j = 0; j < 1010; j++) fill(dist[i][j], dist[i][j] + 1010, 1e7);
  for (int i = 0; i < 3; i++) fill(best[i], best[i] + 3, 1e7);
  for (int k = 0; k < 3; k++) {
    queue<pair<pair<int, int>, int> > q;
    memset(vis, 0, sizeof(vis));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) {
        if (b[i][j] == k + 49) q.push(make_pair((make_pair((i), (j))), (-1)));
      }
    while (q.size()) {
      int x = q.front().first.first;
      int y = q.front().first.second;
      int d = q.front().second;
      q.pop();
      if (x < 0 || y < 0 || x >= n || y >= m || b[x][y] == '#' || vis[x][y])
        continue;
      vis[x][y] = 1;
      dist[k][x][y] = max(0, d);
      if (b[x][y] >= '1' && b[x][y] <= '3') {
        int t = b[x][y] - 49;
        best[k][t] = best[t][k] = min(best[t][k], max(0, d));
      }
      for (int i = 0; i < 4; i++) {
        int dx = x + dir[i].first;
        int dy = y + dir[i].second;
        q.push(make_pair((make_pair((dx), (dy))), (d + 1)));
      }
    }
  }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int now = 0;
      for (int k = 0; k < 3; k++) now += dist[k][i][j];
      res = min(now + 1, res);
    }
  for (int i = 0; i < 3; i++) {
    int now = 0;
    for (int j = 0; j < 3; j++) now += best[i][j];
    res = min(now, res);
  }
  cout << (res >= n * m ? -1 : res) << endl;
  return 0;
}
