#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e3 + 10;
const int INF = 1e8;
int n, m;
char mp[MAX][MAX] = {0};
int d[3][MAX][MAX] = {0};
int moves[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int nmoves = 4;
int mn[3][3] = {0};
void clear() {
  memset(mp, 0, sizeof(mp));
  for (int i = 0; i < MAX; i++)
    for (int j = 0; j < MAX; j++)
      for (int c = 0; c < 3; c++) d[c][i][j] = INF;
  for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++) mn[i][j] = INF;
}
void bfs(int country) {
  priority_queue<pair<int, pair<int, int> > > q;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (int(mp[i][j]) - '1' == country) {
        q.push(pair<int, pair<int, int> >(0, pair<int, int>(i, j)));
        d[country][i][j] = 0;
      }
  while (!q.empty()) {
    pair<int, pair<int, int> > a = q.top();
    q.pop();
    int x = a.second.first;
    int y = a.second.second;
    int distance = -a.first;
    if (mp[x][y] != '.' && mp[x][y] != '#' && mp[x][y] - '1' != country) {
      int other_country = mp[x][y] - '1';
      int tmin = mn[country][other_country];
      tmin = min(tmin, distance - 1);
      mn[country][other_country] = mn[other_country][country] = tmin;
    }
    for (int i = 0; i < nmoves; i++) {
      int nx = x + moves[i][0];
      int ny = y + moves[i][1];
      if (nx >= 0 && nx < n && ny >= 0 && ny < m)
        if (d[country][nx][ny] == INF && mp[nx][ny] != '#') {
          q.push(pair<int, pair<int, int> >(-(distance + 1),
                                            pair<int, int>(nx, ny)));
          d[country][nx][ny] = distance + 1;
        }
    }
  }
}
void solve() {
  for (int i = 0; i < n; i++) scanf("%s", mp[i]);
  bfs(0);
  bfs(1);
  bfs(2);
  int ans = INF;
  ans = min(ans, mn[0][1] + mn[1][2]);
  ans = min(ans, mn[0][2] + mn[1][2]);
  ans = min(ans, mn[0][2] + mn[0][1]);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (mp[i][j] == '.')
        ans = min(ans, d[0][i][j] + d[1][i][j] + d[2][i][j] - 2);
  printf("%d\n", ans == INF ? -1 : ans);
}
int main() {
  while (scanf("%d%d", &n, &m) == 2) {
    clear();
    solve();
  }
  return 0;
}
