#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
char board[1005][1005];
int n, m, ans = 1e9;
int dist[4][1005][1005];
void bfs(int type) {
  deque<pair<int, int> > Q;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      dist[type][i][j] = 1e9;
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (board[i][j] == '0' + type) {
        dist[type][i][j] = 0;
        Q.push_back(make_pair(i, j));
      }
    }
  }
  while (!Q.empty()) {
    pair<int, int> t = Q.front();
    Q.pop_front();
    for (int dir = 0; dir < 4; dir++) {
      int nx = dx[dir] + t.first;
      int ny = dy[dir] + t.second;
      if (nx < 1 || ny < 1 || nx > n || ny > m) {
        continue;
      }
      if (dist[type][nx][ny] != 1e9 || board[nx][ny] == '#') {
        continue;
      }
      if (board[nx][ny] == '.') {
        dist[type][nx][ny] = dist[type][t.first][t.second] + 1;
        Q.push_back(make_pair(nx, ny));
      } else {
        dist[type][nx][ny] = dist[type][t.first][t.second];
        Q.push_front(make_pair(nx, ny));
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> board[i][j];
    }
  }
  for (int i = 1; i <= 3; i++) {
    bfs(i);
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (dist[1][i][j] == 1e9 || dist[2][i][j] == 1e9 ||
          dist[3][i][j] == 1e9) {
        continue;
      }
      if (board[i][j] == '.') {
        ans = min(ans, dist[1][i][j] + dist[2][i][j] + dist[3][i][j] - 2);
      } else {
        ans = min(ans, dist[1][i][j] + dist[2][i][j] + dist[3][i][j]);
      }
    }
  }
  if (ans == 1e9) {
    cout << -1;
  } else {
    cout << ans;
  }
  return 0;
}
