#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e3 + 10;
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {-1, 0, 1, 0};
char a[maxN][maxN];
bool mark[maxN][maxN];
int n, m, dis[4][maxN][maxN];
bool valid(int x, int y) {
  return (x >= 1 && x <= n && y >= 1 && y <= m && a[x][y] != '#');
}
void bfs(int num) {
  queue<pair<int, int> > q;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      dis[num][i][j] = 1e9;
      if (a[i][j] - '0' == num) {
        q.push(make_pair(i, j));
        dis[num][i][j] = 0;
      }
    }
  while (!q.empty()) {
    pair<int, int> cur = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int newx = cur.first + dx[i], newy = cur.second + dy[i];
      if (!valid(newx, newy)) continue;
      if (dis[num][newx][newy] >
          dis[num][cur.first][cur.second] + (a[newx][newy] == '.')) {
        q.push(make_pair(newx, newy));
        dis[num][newx][newy] =
            dis[num][cur.first][cur.second] + (a[newx][newy] == '.');
      }
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> a[i][j];
  for (int i = 1; i <= 3; i++) bfs(i);
  int res = 1e9;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (a[i][j] != '#') {
        if (dis[1][i][j] == 1e9 || dis[2][i][j] == 1e9 || dis[3][i][j] == 1e9)
          continue;
        int tmp = dis[1][i][j] + dis[2][i][j] + dis[3][i][j] -
                  (2 * (int)(a[i][j] == '.'));
        res = min(tmp, res);
      }
  if (res == 1e9)
    cout << -1;
  else
    cout << res;
  cout << endl;
  return 0;
}
