#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
char mp[N][N];
int n, m, dis[4][N][N], d[4][4], f[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
struct node {
  int x, y, t;
};
queue<node> q1, q2, q3;
bool vis[4][N][N];
bool judge(int x, int y) {
  if (x < 0 || x >= n || y < 0 || y >= m || mp[x][y] == '#') return false;
  return true;
}
void BFS(int b, queue<node> &q) {
  while (!q.empty()) {
    node s = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int xx = f[i][0] + s.x, yy = f[i][1] + s.y;
      if (judge(xx, yy) && !vis[b][xx][yy]) {
        if (mp[xx][yy] == '0' + b) continue;
        if (mp[xx][yy] == '1')
          d[b][1] = min(d[b][1], s.t);
        else if (mp[xx][yy] == '2')
          d[b][2] = min(d[b][2], s.t);
        else if (mp[xx][yy] == '3')
          d[b][3] = min(d[b][3], s.t);
        vis[b][xx][yy] = 1;
        dis[b][xx][yy] = s.t;
        q.push({xx, yy, s.t + 1});
      }
    }
  }
  while (!q.empty()) q.pop();
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      for (int k = 1; k < 4; k++) dis[k][i][j] = 1e8;
  for (int i = 1; i <= 3; i++)
    for (int j = 1; j <= 3; j++) d[i][j] = 1e8;
  for (int i = 0; i < n; i++) {
    scanf("%s", mp[i]);
    for (int j = 0; j < m; j++) {
      if (mp[i][j] == '1')
        q1.push({i, j, 0}), vis[1][i][j] = 1, dis[1][i][j] = 0;
      else if (mp[i][j] == '2')
        q2.push({i, j, 0}), vis[2][i][j] = 1, dis[2][i][j] = 0;
      else if (mp[i][j] == '3')
        q3.push({i, j, 0}), vis[3][i][j] = 1, dis[3][i][j] = 0;
    }
  }
  BFS(1, q1);
  BFS(2, q2);
  BFS(3, q3);
  int ans = min({d[1][2] + d[1][3], d[1][2] + d[2][3], d[2][3] + d[1][3]});
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      ans = min(ans, dis[1][i][j] + dis[2][i][j] + dis[3][i][j] +
                         (mp[i][j] == '.' ? 1 : 0));
  if (ans >= 1e8)
    printf("-1\n");
  else
    printf("%d\n", ans);
  return 0;
}
