#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
const int INFP = 0x0f0f0f0f;
struct Node {
  int x, y, t;
  Node() {}
  Node(int x, int y, int t) : x(x), y(y), t(t) {}
} Q[1000010];
int n, m;
char G[N][N];
int p1[4][2], vis[N][N];
int dis1[N][N][4], dis2[4][4];
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void init() {
  memset(dis1, 0x0f, sizeof(dis1));
  for (int i = 1; i <= 3; i++)
    for (int j = 1; j <= 3; j++)
      if (i == j)
        dis2[i][j] = 0;
      else
        dis2[i][j] = INFP;
}
bool OK(int x, int y) {
  if (x < 0 || x >= n || y < 0 || y >= m) return false;
  return true;
}
void BFS(int num) {
  int front = 1, rear = 1;
  Q[front] = Node(p1[num][0], p1[num][1], 0);
  while (front <= rear) {
    Node u = Node(Q[front].x, Q[front].y, Q[front].t);
    front++;
    for (int i = 0; i < 4; i++) {
      int xx = u.x + dir[i][0];
      int yy = u.y + dir[i][1];
      if (OK(xx, yy) && !vis[xx][yy] && G[xx][yy] - '0' == num) {
        vis[xx][yy] = 1;
        rear++;
        dis1[xx][yy][num] = 0;
        Q[rear] = Node(xx, yy, 0);
      }
    }
  }
  front = 1;
  while (front <= rear) {
    Node u = Node(Q[front].x, Q[front].y, Q[front].t);
    front++;
    for (int i = 0; i < 4; i++) {
      int xx = u.x + dir[i][0];
      int yy = u.y + dir[i][1];
      int tt = u.t;
      if (OK(xx, yy) && G[xx][yy] != '#' && !vis[xx][yy]) {
        vis[xx][yy] = 1;
        if (G[xx][yy] == '.') {
          dis1[xx][yy][num] = tt + 1;
          rear++;
          Q[rear] = Node(xx, yy, tt + 1);
        } else {
          dis1[xx][yy][num] = tt + 1;
          int id = G[xx][yy] - '0';
          dis2[num][id] = min(dis2[num][id], tt + 1);
          rear++;
          Q[rear] = Node(xx, yy, tt + 1);
        }
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%s", G[i]);
    for (int j = 0; j < m; j++) {
      if (G[i][j] != '.' && G[i][j] != '#') {
        p1[G[i][j] - '0'][0] = i;
        p1[G[i][j] - '0'][1] = j;
      }
    }
  }
  init();
  for (int i = 1; i <= 3; i++) {
    memset(vis, 0, sizeof(vis));
    BFS(i);
  }
  int ans = INFP;
  ans = min(ans, dis2[1][2] + dis2[1][3] - 2);
  ans = min(ans, dis2[1][2] + dis2[2][3] - 2);
  ans = min(ans, dis2[1][3] + dis2[2][3] - 2);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (G[i][j] == '#') continue;
      if (G[i][j] == '.')
        ans = min(ans, dis1[i][j][1] + dis1[i][j][2] + dis1[i][j][3] - 2);
      else
        ans = min(ans, dis1[i][j][1] + dis1[i][j][2] + dis1[i][j][3] - 2);
    }
  }
  if (ans >= INFP - 2)
    printf("-1\n");
  else
    printf("%d\n", ans);
  return 0;
}
