#include <bits/stdc++.h>
using namespace std;
template <class T>
bool uax(T& a, const T& b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
bool uin(T& a, const T& b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, m;
  const int noroad = '#' - '1';
  cin >> n >> m;
  vector<vector<int> > g(n + 2, vector<int>(m + 2, noroad));
  vector<vector<vector<int> > > d(
      3, vector<vector<int> >(n + 2, vector<int>(m + 2, 1e8)));
  vector<pair<int, int> > s(3);
  vector<pair<int, int> > dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
  for (int i = 0; i < (int)(n); ++i) {
    for (int j = 0; j < (int)(m); ++j) {
      char c;
      cin >> c;
      g[i + 1][j + 1] = c - '1';
      if (c > '0' && c < '4') {
        s[c - '1'] = make_pair(i + 1, j + 1);
      }
    }
  }
  auto cost = [](int a, int b) -> int {
    int c = 1;
    if (b >= 0 && a >= 0) c = 0;
    return c;
  };
  auto bfs = [&](int c) {
    deque<pair<int, int> > q;
    vector<vector<int> > v(n, vector<int>(m, 0));
    q.push_back(s[c]);
    d[c][s[c].first][s[c].second] = 0;
    while (!q.empty()) {
      int x = q.front().first;
      int y = q.front().second;
      q.pop_front();
      for (auto dir : dirs) {
        pair<int, int> to = {x + dir.first, y + dir.second};
        if (g[to.first][to.second] != noroad) {
          if (cost(g[to.first][to.second], g[x][y]) == 0) {
            if (uin(d[c][to.first][to.second], d[c][x][y])) {
              q.push_front(to);
            }
          } else {
            if (uin(d[c][to.first][to.second], d[c][x][y] + 1)) {
              q.push_back(to);
            }
          }
        }
      }
    }
  };
  bfs(0);
  bfs(1);
  bfs(2);
  int ans = 1e8;
  for (int i = 0; i < (int)(n); ++i) {
    for (int j = 0; j < (int)(m); ++j) {
      int sum = d[0][i + 1][j + 1] + d[1][i + 1][j + 1] + d[2][i + 1][j + 1];
      uin(ans, sum);
    }
  }
  if (ans == 1e8)
    ans = -1;
  else {
    int d01 = d[0][s[1].first][s[1].second];
    int d12 = d[1][s[2].first][s[2].second];
    int d20 = d[2][s[0].first][s[0].second];
    int z = 0;
    if (d01 == 0) z++;
    if (d12 == 0) z++;
    if (d20 == 0) z++;
    if (z == 1) {
      ans -= 1;
    } else if (z == 0) {
      ans -= 2;
    }
  }
  cout << ans;
  return 0;
}
