#include <bits/stdc++.h>
using namespace std;
const int mod = int(1e9) + 7, INF = 0x3ffffff, maxn = 1e3 + 40;
int n, m;
char G[maxn][maxn];
bool used[maxn][maxn];
int dp[3][maxn][maxn], dirx[4] = {-1, 1, 0, 0}, diry[4] = {0, 0, -1, 1};
void bfs(char c) {
  queue<pair<int, int> > q;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (G[i][j] == c) {
        q.push(make_pair(i, j));
        dp[c - '1'][i][j] = 0;
      }
  while (!q.empty()) {
    pair<int, int> t = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int x = t.first + dirx[i], y = t.second + diry[i];
      if (x < 1 || y < 1 || x > n || y > m || G[x][y] == '#') continue;
      if (dp[c - '1'][x][y] >
          dp[c - '1'][t.first][t.second] + (G[t.first][t.second] == '.')) {
        dp[c - '1'][x][y] =
            dp[c - '1'][t.first][t.second] + (G[t.first][t.second] == '.');
        q.push(make_pair(x, y));
      }
    }
  }
}
int main(void) {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> G[i][j];
  for (int i = 0; i < 3; i++)
    for (int j = 0; j <= n; j++)
      for (int k = 0; k <= m; k++) dp[i][j][k] = INF;
  for (int i = 0; i < 3; i++) bfs(i + '1');
  int ans = INF;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      ans =
          min(ans, dp[0][i][j] + dp[1][i][j] + dp[2][i][j] + (G[i][j] == '.'));
  cout << (ans == INF ? -1 : ans) << endl;
  return 0;
}
