#include <bits/stdc++.h>
using namespace std;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
string s[1000];
int d[3][1000][1000];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; ++i) {
    cin >> s[i];
    for (int j = 0; j < m; ++j) {
      for (int k = 0; k < 3; ++k) {
        d[k][i][j] = -1;
      }
    }
  }
  for (int k = 0; k < 3; ++k) {
    deque<pair<int, int>> q;
    char c = '1' + k;
    for (int i = 0; q.empty() && i < n; ++i) {
      for (int j = 0; q.empty() && j < m; ++j) {
        if (s[i][j] == c) {
          d[k][i][j] = 0;
          q.emplace_back(i, j);
        }
      }
    }
    while (!q.empty()) {
      auto pair = q.front();
      q.pop_front();
      int x = pair.first;
      int y = pair.second;
      for (int l = 0; l < 4; ++l) {
        int x1 = x + dx[l];
        if (x1 < 0 || x1 >= n) continue;
        int y1 = y + dy[l];
        if (y1 < 0 || y1 >= m) continue;
        if (d[k][x1][y1] >= 0) continue;
        if (s[x1][y1] == '#') continue;
        if (s[x1][y1] == '.') {
          d[k][x1][y1] = d[k][x][y] + 1;
          q.emplace_back(x1, y1);
        } else {
          d[k][x1][y1] = d[k][x][y];
          q.emplace_front(x1, y1);
        }
      }
    }
  }
  int ans = -1;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      if (d[0][i][j] >= 0 && d[1][i][j] >= 0 && d[2][i][j] >= 0) {
        int ans2 = d[0][i][j] + d[1][i][j] + d[2][i][j];
        if (s[i][j] == '.') ans2 -= 2;
        if (ans == -1 || ans > ans2) ans = ans2;
      }
  cout << ans;
}
