#include <bits/stdc++.h>
using namespace std;
const int INF = 100000000;
struct coord {
  short x, y, color;
  coord(int _x, int _y, int _color) {
    x = _x;
    y = _y;
    color = _color;
  }
  coord() {
    x = 0;
    y = 0;
  }
};
vector<string> g;
vector<vector<vector<int>>> d;
coord first, second, third;
int n, m;
bool check(coord v) {
  if (v.x >= 1 && v.x <= n && v.y >= 1 && v.y <= m && g[v.x][v.y] != '#')
    return true;
  else
    return false;
}
void run_edge(coord v, int dir_x, int dir_y, deque<coord>& q) {
  coord to = v;
  to.x += dir_x;
  to.y += dir_y;
  if (check(to)) {
    if (g[to.x][to.y] >= '1' && g[to.x][to.y] <= '3') {
      if (d[to.x][to.y][to.color] > d[v.x][v.y][v.color]) {
        d[to.x][to.y][to.color] = d[v.x][v.y][v.color];
        q.push_front(to);
      }
    } else {
      if (d[to.x][to.y][to.color] > d[v.x][v.y][v.color] + 1) {
        d[to.x][to.y][to.color] = d[v.x][v.y][v.color] + 1;
        q.push_back(to);
      }
    }
  }
}
void solve() {
  d.assign(n + 1, vector<vector<int>>(m + 1, vector<int>(4, INF)));
  deque<coord> q;
  q.push_back(first);
  q.push_back(second);
  q.push_back(third);
  d[first.x][first.y][1] = 0;
  d[second.x][second.y][2] = 0;
  d[third.x][third.y][3] = 0;
  while (!q.empty()) {
    coord v = q.front();
    q.pop_front();
    run_edge(v, 0, 1, q);
    run_edge(v, 1, 0, q);
    run_edge(v, 0, -1, q);
    run_edge(v, -1, 0, q);
  }
  int ans = INF;
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (ans > d[i][j][1] + d[i][j][2] + d[i][j][3] - (g[i][j] == '.') * 2) {
        ans = d[i][j][1] + d[i][j][2] + d[i][j][3] - (g[i][j] == '.') * 2;
      }
    }
  }
  if (ans >= INF)
    cout << -1;
  else
    cout << ans;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  g.assign(n + 1, string(m + 1, ' '));
  for (int i = 1; i <= n; ++i) {
    string s;
    cin >> s;
    for (int j = 1; j <= m; ++j) {
      g[i][j] = s[j - 1];
      if (g[i][j] == '1') {
        first.x = i;
        first.y = j;
        first.color = 1;
      }
      if (g[i][j] == '2') {
        second.x = i;
        second.y = j;
        second.color = 2;
      }
      if (g[i][j] == '3') {
        third.x = i;
        third.y = j;
        third.color = 3;
      }
    }
  }
  solve();
  return 0;
}
