#include <bits/stdc++.h>
using namespace std;
int dis[1024 * 1024][3];
int mp[1024][1024];
vector<int> adj[1024 * 1024];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int p = 4;
void bfs(int np) {
  for (int i = 1; i < p; i++) dis[i][np] = 0x3F3F3F3F;
  dis[np][np] = 0;
  queue<int> que;
  que.push(np);
  while (!que.empty()) {
    int u = que.front();
    que.pop();
    for (int i = 0; i < adj[u].size(); i++) {
      int v = adj[u][i];
      if (dis[v][np] == 0x3F3F3F3F) {
        dis[v][np] = dis[u][np] + 1;
        que.push(v);
      }
    }
  }
}
int main() {
  string arr[1024];
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
    for (int j = 0; j < m; j++) {
      if (arr[i][j] == '.') mp[i][j] = p++;
      if (isdigit(arr[i][j])) mp[i][j] = arr[i][j] - '0';
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      for (int x = 0; x < 4; x++) {
        int nx = i + dx[x], ny = j + dy[x];
        if (((nx) >= 0 && (nx) < (n)) && ((ny) >= 0 && (ny) < (m)) &&
            arr[nx][ny] != '#')
          adj[mp[i][j]].push_back(mp[nx][ny]);
      }
    }
  }
  for (int i = 1; i < p; i++) {
    sort(adj[i].begin(), adj[i].end());
    adj[i].erase(unique(adj[i].begin(), adj[i].end()), adj[i].end());
  }
  for (int i = 1; i < 4; i++) bfs(i);
  int ans = 0x3F3F3F3F;
  for (int i = 1; i < p; i++) {
    if (dis[i][1] != 0x3F3F3F3F && dis[i][2] != 0x3F3F3F3F &&
        dis[i][3] != 0x3F3F3F3F)
      ans = min(ans, dis[i][1] + dis[i][2] + dis[i][3] - 2);
  }
  if (ans == 0x3F3F3F3F)
    puts("-1");
  else
    printf("%d\n", ans);
  return 0;
}
