#include <bits/stdc++.h>
using namespace std;
int n, m, mat[1005][1005], mark[1005][1005],
    yon[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}, cev[4][1005][1005];
char chs[1005][1005];
queue<pair<pair<int, int>, int> > q[4];
void bfs(int s) {
  for (int i = 0; i < n + 5; i++)
    for (int j = 0; j < m + 5; j++) mark[i][j] = mat[i][j];
  while (!q[s].empty()) {
    pair<pair<int, int>, int> tut = q[s].front();
    int i = tut.first.first, j = tut.first.second;
    q[s].pop();
    if (mark[tut.first.first][tut.first.second] == 0) continue;
    mark[tut.first.first][tut.first.second] = 0;
    cev[s][tut.first.first][tut.first.second] = tut.second;
    for (int y = 0; y < 4; y++)
      if (mark[i + yon[y][0]][j + yon[y][1]])
        q[s].push(
            make_pair(make_pair(i + yon[y][0], j + yon[y][1]), tut.second + 1));
  }
}
int main() {
  long long int cevap = 1000000000;
  long long int cev1 = 1000000000, cev2 = 1000000000, cev3 = 1000000000;
  scanf("%d %d", &n, &m);
  for (int y = 1; y < 4; y++)
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) cev[y][i][j] = 1000000000;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      char c;
      scanf(" %c", &c);
      if (c == '.') mat[i][j] = 1;
      chs[i][j] = c;
      if (c == '1')
        for (int y = 0; y < 4; y++) {
          if (chs[i + yon[y][0]][j + yon[y][1]] == '2') cev1 = 0;
          if (chs[i + yon[y][0]][j + yon[y][1]] == '3') {
            cev3 = 0;
          }
          q[1].push(make_pair(make_pair(i + yon[y][0], j + yon[y][1]), 0));
        }
      if (c == '2')
        for (int y = 0; y < 4; y++) {
          if (chs[i + yon[y][0]][j + yon[y][1]] == '1') cev1 = 0;
          if (chs[i + yon[y][0]][j + yon[y][1]] == '3') cev2 = 0;
          q[2].push(make_pair(make_pair(i + yon[y][0], j + yon[y][1]), 0));
        }
      if (c == '3')
        for (int y = 0; y < 4; y++) {
          if (chs[i + yon[y][0]][j + yon[y][1]] == '1') {
            cev3 = 0;
          }
          if (chs[i + yon[y][0]][j + yon[y][1]] == '2') cev2 = 0;
          q[3].push(make_pair(make_pair(i + yon[y][0], j + yon[y][1]), 0));
        }
    }
  bfs(1);
  bfs(2);
  bfs(3);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      cevap = min(cevap, 1ll * cev[1][i][j] + cev[2][i][j] + cev[3][i][j] + 1);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      cev1 = min(cev1, 1ll * cev[1][i][j] + cev[2][i][j] + 1);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      cev2 = min(cev2, 1ll * cev[2][i][j] + cev[3][i][j] + 1);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      cev3 = min(cev3, 1ll * cev[1][i][j] + cev[3][i][j] + 1);
  cevap = min(cevap, 1ll * cev1 + cev2);
  cevap = min(cevap, 1ll * cev1 + cev3);
  cevap = min(cevap, 1ll * cev2 + cev3);
  if (1000000000 <= cevap)
    printf("-1");
  else
    cout << cevap << endl;
}
