#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 18;
const long long MAXK = 1 << 18;
const long long dx[] = {-1, 0, 1, 0};
const long long dy[] = {0, 1, 0, -1};
const long long con[] = {2, 3, 0, 1};
char maze[MAXN][MAXN];
bool vis[MAXN][MAXN][MAXK];
struct snk {
  long long x, y, sta;
  snk(long long a, long long b, long long c) { x = a, y = b, sta = c; }
};
queue<snk> que;
queue<long long> dis;
long long n, m;
long long sx, sy, sst, kx, ky, len, ex, ey;
void input() {
  cin >> n >> m;
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) {
      cin >> maze[i][j];
      if (maze[i][j] == '1')
        sx = i, sy = j;
      else if (maze[i][j] >= '1' && maze[i][j] <= '9') {
        long long tmp = maze[i][j] - '0';
        if (tmp > len) {
          len = tmp;
          kx = i;
          ky = j;
        }
      } else if (maze[i][j] == '@') {
        ex = i;
        ey = j;
      }
    }
  }
}
void init() {
  long long x = kx, y = ky;
  while (maze[x][y] != '1') {
    for (long long i = 0; i < 4; i++) {
      long long nx = x + dx[i];
      long long ny = y + dy[i];
      if (maze[nx][ny] == maze[x][y] - 1) {
        x = nx;
        y = ny;
        sst = (sst << 2) | con[i];
        break;
      }
    }
  }
}
long long cut(long long x) {
  if ((x & (1 << (len * 2 - 1))) != 0) x = x - (1 << (len * 2 - 1));
  if ((x & (1 << (len * 2 - 2))) != 0) x = x - (1 << (len * 2 - 2));
  return x;
}
bool check(long long x, long long y, long long st) {
  long long cnt = 1;
  long long xx = x, yy = y, las = -1;
  while (1) {
    long long tmp = st;
    tmp >>= 2;
    tmp <<= 2;
    long long dir = st - tmp;
    long long nx = x + dx[dir];
    long long ny = y + dy[dir];
    if (las == con[dir]) return false;
    las = dir;
    x = nx;
    y = ny;
    st >>= 2;
    cnt++;
    if (xx == nx && yy == ny) return false;
    if (cnt == len) break;
  }
  return true;
}
long long bfs() {
  que.push(snk(sx, sy, sst));
  dis.push(0);
  vis[sx][sy][sst] = 1;
  while (!que.empty()) {
    snk cur = que.front();
    que.pop();
    long long d = dis.front();
    dis.pop();
    long long cx = cur.x;
    long long cy = cur.y;
    long long csta = cur.sta;
    for (long long i = 0; i < 4; i++) {
      long long nx = cx + dx[i];
      long long ny = cy + dy[i];
      if (nx == ex && ny == ey) return d + 1;
      long long nst = (csta << 2) | con[i];
      nst = cut(nst);
      if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
      if (vis[nx][ny][nst]) continue;
      if (maze[nx][ny] != '#' && check(nx, ny, nst)) {
        que.push(snk(nx, ny, nst));
        dis.push(d + 1);
        vis[nx][ny][nst] = 1;
      }
    }
  }
  return -1;
}
int main() {
  input();
  init();
  cout << bfs() << endl;
  return 0;
}
