#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long qpow(long long x, long long k) {
  return k == 0 ? 1
                : 1ll * qpow(1ll * x * x % mod, k >> 1) * (k & 1 ? x : 1) % mod;
}
const int Maxn = 20;
int n, m, l = 0;
char s[Maxn][Maxn];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
pair<int, int> tar;
int mask;
class state {
 public:
  pair<int, int> head;
  int path;
  bool move(int step) {
    int nx = head.first - dx[step], ny = head.second - dy[step];
    if (s[nx][ny] == '#') return false;
    int tmp = path, x = head.first, y = head.second, go;
    for (int i = 1; i < l; i++) {
      go = tmp & 3;
      x += dx[go];
      y += dy[go];
      if (x == nx && y == ny) return false;
      tmp >>= 2;
    }
    return true;
  }
  state get(int step) {
    state nex;
    int nx = head.first - dx[step], ny = head.second - dy[step];
    nex.head = pair<int, int>(nx, ny);
    nex.path = ((path << 2) + step) & mask;
    return nex;
  }
  bool operator<(const state& o) const {
    return (head < o.head) || (head == o.head && path < o.path);
  }
};
state init(int x, int y) {
  state ret;
  ret.head = pair<int, int>(x, y);
  int path = 0;
  while (true) {
    bool flag = true;
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i], ny = y + dy[i];
      if (s[nx][ny] == s[x][y] + 1) {
        flag = false;
        x = nx;
        y = ny;
        path |= i << (l << 1);
        break;
      }
    }
    if (flag) break;
    l++;
  }
  mask = (1 << (l << 1)) - 1;
  ret.path = path;
  return ret;
}
map<state, int> mp;
int main() {
  scanf("%d%d", &n, &m);
  memset(s, '#', sizeof(s));
  for (int i = 1; i <= n; i++) {
    scanf("%s", s[i] + 1);
    s[i][m + 1] = '#';
  }
  state S;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (s[i][j] == '1') {
        S = init(i, j);
      }
      if (s[i][j] == '@') {
        tar = pair<int, int>(i, j);
      }
    }
  }
  queue<state> q;
  mp[S] = 0;
  q.push(S);
  while (!q.empty()) {
    state now = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      if (now.move(i)) {
        state nex = now.get(i);
        if (mp.find(nex) == mp.end()) {
          mp[nex] = mp[now] + 1;
          if (nex.head == tar) {
            printf("%d\n", mp[nex]);
            return 0;
          }
          q.push(nex);
        }
      }
    }
  }
  printf("-1\n");
  return 0;
}
