#include <bits/stdc++.h>
using namespace std;
struct point {
  int x, y;
  bool operator==(point h) { return x == h.x && y == h.y; }
} ed;
struct node {
  point ps[10];
  int st;
} q[1000005], tp;
map<pair<long long, long long>, bool> h1;
long long mod = 1e12;
int n, m, f, r, dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}, l;
char tm[20][20];
bool flg, fnd;
int max(int x, int y) { return x > y ? x : y; }
bool hsh(node k) {
  long long t = 0, t2 = 0;
  for (int i = 1; i <= l; i++) t = t * n + k.ps[i].x;
  for (int i = 1; i <= l; i++) t2 = t2 * m + k.ps[i].y;
  pair<long long, long long> tt(t, t2);
  if (h1[tt]) return 0;
  h1[tt] = 1;
  return 1;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", tm[i]);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      if (tm[i][j] > 47 && tm[i][j] < 58)
        q[0].ps[tm[i][j] - 48].x = i, q[0].ps[tm[i][j] - 48].y = j;
      if (tm[i][j] == '@') ed.x = i, ed.y = j;
      l = max(l, (tm[i][j] > 47 && tm[i][j] < 58) ? tm[i][j] - 48 : 0);
    }
  while (f >= r) {
    tp = q[r];
    if (tp.ps[1] == ed) {
      printf("%d", tp.st);
      fnd = 1;
      break;
    }
    for (int i = 0; i < 4; i++) {
      if (i != 0) tp = q[r];
      int t1 = tp.ps[1].x + dx[i], t2 = tp.ps[1].y + dy[i];
      if (t1 < 0 || t1 >= n || t2 < 0 || t2 >= m) continue;
      if (tm[t1][t2] == '#') continue;
      for (int j = l; j > 1; j--) tp.ps[j] = tp.ps[j - 1];
      tp.ps[1].x = t1;
      tp.ps[1].y = t2;
      for (int j = 2; j <= l; j++)
        if (tp.ps[1] == tp.ps[j]) {
          flg = 1;
          break;
        }
      if (flg) {
        flg = 0;
        continue;
      }
      if (!hsh(tp)) continue;
      tp.st++;
      q[++f] = tp;
    }
    r++;
  }
  if (!fnd) printf("-1");
  return 0;
}
