#include <bits/stdc++.h>
using namespace std;
int n, m, k;
char A[16][16];
int R[15][15][1 << 16];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};
queue<pair<int, int> > Q0;
queue<int> Q1;
int C[15][15];
int F(int a, int b) {
  for (int(i) = (0); (i) < (4); ++(i))
    if (dx[i] == a && dy[i] == b) return i;
}
bool OK(int x, int y) { return (x >= 0 && y >= 0 && x < n && y < m); }
int Code(vector<int> &X) {
  int p = 1, res = 0;
  for (int(i) = (0); (i) < (X.size()); ++(i)) {
    res += X[i] * p;
    p *= 4;
  }
  return res;
}
vector<int> Decode(int &xx) {
  int x = xx;
  vector<int> Res;
  while (x > 0) {
    Res.push_back(x % 4);
    x /= 4;
  }
  while (Res.size() < k - 1) Res.push_back(0);
  return Res;
}
int main() {
  memset(R, -1, sizeof(R));
  cin >> n >> m;
  for (int(i) = (0); (i) < (n); ++(i)) scanf("%s", A[i]);
  for (int(i) = (0); (i) < (n); ++(i))
    for (int(j) = (0); (j) < (m); ++(j))
      if (A[i][j] >= '1' && A[i][j] <= '9') k++;
  vector<int> S;
  vector<pair<int, int> > P;
  for (int(i) = (0); (i) < (k); ++(i))
    for (int(x) = (0); (x) < (n); ++(x))
      for (int(y) = (0); (y) < (m); ++(y))
        if (A[x][y] == char('1' + i)) P.push_back(make_pair(x, y));
  for (int(i) = (1); (i) < (P.size()); ++(i))
    S.push_back(F(P[i].first - P[i - 1].first, P[i].second - P[i - 1].second));
  Q0.push(make_pair(P[0].first, P[0].second));
  Q1.push(Code(S));
  R[P[0].first][P[0].second][Code(S)] = 0;
  int oper = 0;
  int cnt = 1;
  while (!Q0.empty()) {
    oper++;
    if (oper > 700000) break;
    pair<int, int> t;
    vector<int> T;
    t = Q0.front();
    Q0.pop();
    T = Decode(Q1.front());
    Q1.pop();
    int x = t.first;
    int y = t.second;
    if (A[x][y] == '@') {
      cout << R[x][y][Code(T)] << endl;
      return 0;
    }
    for (int(i) = (0); (i) < (4); ++(i)) {
      if (i == T[0]) continue;
      int xx = x + dx[i];
      int yy = y + dy[i];
      if (!OK(xx, yy) || A[xx][yy] == '#') continue;
      int tt = (i + 2) % 4;
      int tx = xx, ty = yy;
      C[xx][yy] = cnt;
      bool ok = true;
      for (int(j) = (0); (j) < (k - 1); ++(j)) {
        if (j != 0) {
          tx += dx[T[j - 1]];
          ty += dy[T[j - 1]];
        } else {
          tx += dx[tt];
          ty += dy[tt];
        }
        if (!OK(tx, ty) || (A[tx][ty] == '#')) {
          ok = false;
          break;
        }
        if (C[tx][ty] == cnt) {
          ok = false;
          break;
        }
        C[tx][ty] = cnt;
      }
      cnt++;
      if (!ok) continue;
      vector<int> TT;
      TT.push_back(tt);
      for (int(j) = (0); (j) < (T.size() - 1); ++(j)) TT.push_back(T[j]);
      int d = Code(TT);
      if (R[xx][yy][d] == -1) {
        Q0.push(make_pair(xx, yy));
        Q1.push(d);
        R[xx][yy][d] = R[x][y][Code(T)] + 1;
      }
    }
  }
  cout << -1 << endl;
  return 0;
}
