#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e8;
int n, m;
deque<pair<int, int> > q;
int a[1010][1010];
pair<int, int> b[4];
pair<int, int> c[5][1010][1010];
bool used[1010][1010];
const int si[4] = {0, -1, 0, 1};
const int sj[4] = {1, 0, -1, 0};
bool exist(int x, int y) {
  return (x >= 0 && y >= 0 && x < n && y < m && a[x][y] != -1);
}
void check(int i, int j, int t, int v) {
  if (a[i][j] == 0) t++;
  if (c[v][i][j].first > t) {
    if (c[v][i][j].second)
      q.push_front(make_pair(i, j));
    else
      q.push_back(make_pair(i, j));
    c[v][i][j] = make_pair(t, true);
  }
}
void bfs(int v) {
  int x1 = b[v].first;
  int y1 = b[v].second;
  q.push_back(make_pair(x1, y1));
  c[v][x1][y1] = make_pair(0, false);
  while (!q.empty()) {
    int x = q.front().first;
    int y = q.front().second;
    q.pop_front();
    c[v][x][y].second = true;
    for (int it = 0; it < 4; it++) {
      int x1 = x + si[it];
      int y1 = y + sj[it];
      if (!exist(x1, y1)) continue;
      check(x1, y1, c[v][x][y].first, v);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      char c;
      cin >> c;
      if (c == '.')
        a[i][j] = 0;
      else if (c == '#')
        a[i][j] = -1;
      else {
        int x = (int)(c - '0');
        a[i][j] = x;
        b[x] = make_pair(i, j);
      }
    }
  }
  for (int k = 1; k < 4; k++)
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) c[k][i][j] = make_pair(INF, false);
  for (int i = 1; i < 4; i++) bfs(i);
  int ans = INF;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] == -1) continue;
      int cur = 0;
      for (int k = 1; k < 4; k++) cur += c[k][i][j].first;
      if (!a[i][j]) cur -= 2;
      ans = min(ans, cur);
    }
  }
  if (ans == INF)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
