#include <bits/stdc++.h>
using namespace std;
int n, m;
char mp[1100][1100];
int visit[3][1100][1100];
void bfs(int a) {
  deque<pair<int, int> > dq;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) visit[a][i][j] = 1e9;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if ((char)'1' + a == mp[i][j])
        dq.push_back(make_pair(i, j)), visit[a][i][j] = 0;
  while (!dq.empty()) {
    pair<int, int> p = dq.front();
    dq.pop_front();
    int x = p.first;
    int y = p.second;
    int d1[4] = {0, 1, 0, -1}, d2[4] = {1, 0, -1, 0};
    for (int i = 0; i < 4; i++) {
      if (x + d1[i] >= n || x + d1[i] < 0 || y + d2[i] >= m || y + d2[i] < 0)
        continue;
      if (mp[x + d1[i]][y + d2[i]] == '#') continue;
      if (visit[a][x + d1[i]][y + d2[i]] != 1e9) continue;
      int cost = (mp[x + d1[i]][y + d2[i]] == '.');
      visit[a][x + d1[i]][y + d2[i]] = visit[a][x][y] + cost;
      if (cost)
        dq.push_back(make_pair(x + d1[i], y + d2[i]));
      else
        dq.push_front(make_pair(x + d1[i], y + d2[i]));
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) cin >> mp[i][j];
  for (int i = 0; i < 3; i++) bfs(i);
  int res = 1e9;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int v = visit[0][i][j] + visit[1][i][j] + visit[2][i][j];
      if (v < 0) continue;
      if (mp[i][j] == '.') v -= 2;
      res = min(res, v);
    }
  if (res >= 1e9)
    cout << -1 << endl;
  else
    cout << res << endl;
  return 0;
}
