#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
vector<vector<char>> gr;
vector<vector<vector<int>>> d;
int n, m;
vector<int> x = {1, -1, 0, 0};
vector<int> y = {0, 0, -1, 1};
void bfs01(int k) {
  deque<pair<int, int>> q;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      if (k == 0 && gr[i][j] == '1') {
        d[0][i][j] = 0;
        q.push_back(make_pair(i, j));
      } else if (k == 1 && gr[i][j] == '2') {
        d[1][i][j] = 0;
        q.push_back(make_pair(i, j));
      } else if (k == 2 && gr[i][j] == '3') {
        d[2][i][j] = 0;
        q.push_back(make_pair(i, j));
      }
    }
  }
  while (!q.empty()) {
    int xx = q.front().second;
    int yy = q.front().first;
    q.pop_front();
    for (int i = 0; i < 4; ++i) {
      int b = x[i] + yy;
      int a = y[i] + xx;
      if (a >= 0 && a < m && b >= 0 && b < n && gr[b][a] != '#') {
        int c = d[k][yy][xx] + (gr[b][a] == '.');
        if (d[k][b][a] > c) {
          d[k][b][a] = c;
          q.push_back(make_pair(b, a));
        }
      }
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  d.assign(3, vector<vector<int>>(n, vector<int>(m, inf)));
  gr.assign(n, vector<char>(m, '.'));
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> gr[i][j];
    }
  }
  bfs01(0);
  bfs01(1);
  bfs01(2);
  int ans = inf;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      if (gr[i][j] != '#') {
        int c = d[0][i][j] + d[1][i][j] + d[2][i][j] - 2 * (gr[i][j] == '.');
        if (c >= 0) {
          ans = min(c, ans);
        }
      }
    }
  }
  if (ans < inf) {
    cout << ans;
  } else {
    cout << -1;
  }
  return 0;
}
