#include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 29;
const long long LINF = 1LL << 50;
const int MAXM = 1e5 + 5;
const int MAXN = 1e5 + 5;
const double PI = acos(-1.0);
const double eps = 1e-6;
int d[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct Node {
  int x, y, steps;
  bool operator<(const Node &i) const { return steps > i.steps; }
  Node() {}
  Node(int a, int b, int s) : x(a), y(b), steps(s) {}
};
int dist[4][4];
int vis[1010][1010][4], n, m;
void func(int x, int y) {
  for (int i = 1; i <= 3; i++)
    for (int j = i + 1; j <= 3; j++)
      if (vis[x][y][i] != -1 && vis[x][y][j] != -1) {
        dist[i][j] = dist[j][i] =
            min(dist[i][j], vis[x][y][i] + vis[x][y][j] - 1);
      }
}
priority_queue<Node> pq;
char mp[1010][1010];
void bfs(int x, int y, int state) {
  Node node(x, y, 0);
  vis[x][y][state] = 0;
  pq.push(node);
  while (!pq.empty()) {
    node = pq.top();
    pq.pop();
    for (int i = 0; i < 4; i++) {
      int x = node.x + d[i][0], y = node.y + d[i][1];
      if (x < 0 || x >= n || y < 0 || y >= m || mp[x][y] == '#') continue;
      if (vis[x][y][state] != -1) continue;
      if (mp[x][y] >= '1' && mp[x][y] <= '3' && mp[x][y] != state + '0') {
        int a = mp[x][y] - '0', b = state;
        dist[a][b] = dist[b][a] = min(dist[a][b], node.steps);
        vis[x][y][state] = dist[a][b];
        continue;
      }
      Node tmp = node;
      tmp.x = x, tmp.y = y;
      if (mp[x][y] == '.') tmp.steps++;
      vis[x][y][state] = tmp.steps;
      pq.push(tmp);
    }
  }
}
int main() {
  memset(vis, -1, sizeof vis);
  for (int i = 1; i <= 3; i++)
    for (int j = 1; j <= 3; j++) dist[i][j] = INF;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", mp[i]);
  int x1, y1, x2, y2, x3, y3;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (mp[i][j] == '1')
        x1 = i, y1 = j;
      else if (mp[i][j] == '2')
        x2 = i, y2 = j;
      else if (mp[i][j] == '3')
        x3 = i, y3 = j;
  bfs(x1, y1, 1);
  bfs(x2, y2, 2);
  bfs(x3, y3, 3);
  int ans = INF;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      if (mp[i][j] >= '1' && mp[i][j] <= '3') continue;
      func(i, j);
      if (vis[i][j][1] != -1 && vis[i][j][2] != -1 && vis[i][j][3] != -1)
        ans = min(vis[i][j][1] + vis[i][j][2] + vis[i][j][3] - 2, ans);
    }
  ans = min(min(dist[1][2] + dist[2][3], ans),
            min(dist[1][2] + dist[1][3], dist[1][3] + dist[2][3]));
  printf("%d\n", ans >= INF ? -1 : ans);
}
