#include <bits/stdc++.h>
using namespace std;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
int n, m, cell[20][20], len, sx, sy, cn, sn, gx, gy;
char chr;
map<int, int> mp;
queue<pair<int, int> > que;
inline bool bound(int x, int y) { return (x >= 0 && x < n && y >= 0 && y < m); }
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    getchar();
    for (int j = 0; j < m; j++) {
      cin >> chr;
      if (chr == '#')
        cell[i][j] = -1;
      else if (chr == '@') {
        cell[i][j] = 0;
        gx = i;
        gy = j;
      } else if (chr == '.')
        cell[i][j] = 0;
      else {
        len = max(chr - '0', len);
        cell[i][j] = chr - '0';
        if (cell[i][j] == 1) {
          sn += i;
          sn <<= 4;
          sn += j;
          sx = i;
          sy = j;
        }
      }
    }
  }
  cn = 2;
  for (int ii = 0; ii < len - 1; ii++) {
    for (int i = 0; i < 4; i++) {
      int nx = sx + dx[i];
      int ny = sy + dy[i];
      if (bound(nx, ny) && cell[nx][ny] == cn) {
        sn <<= 2;
        sn += i;
        cn++;
        sx = nx;
        sy = ny;
        break;
      }
    }
  }
  mp[sn] = 1;
  que.push(pair<int, int>(sn, 0));
  while (!que.empty()) {
    pair<int, int> snake = que.front();
    que.pop();
    int snum = snake.first;
    int scnt = snake.second;
    int sx = ((snum >> (2 * len + 2)) & ((1 << 4) - 1));
    int sy = ((snum >> (2 * (len - 1))) & ((1 << 4) - 1));
    if (sx == gx && sy == gy) {
      cout << scnt << endl;
      return 0;
    }
    for (int ii = 0; ii < 4; ii++) {
      int nsx = sx - dx[ii];
      int nsy = sy - dy[ii];
      if (!bound(nsx, nsy) || cell[nsx][nsy] == -1) continue;
      int ssx = dx[ii];
      int ssy = dy[ii];
      int flag = 1;
      for (int i = 0; i < len - 2; i++) {
        int dir = ((snum >> (2 * len - 2 * i - 4)) & 3);
        ssx += dx[dir];
        ssy += dy[dir];
        if (ssx == 0 && ssy == 0) {
          flag = 0;
          break;
        }
      }
      if (!flag) continue;
      int nsnum = ((snum & ((1 << (2 * (len - 1))) - 3)) >> 2);
      nsnum += (ii << (2 * (len - 2)));
      nsnum += (nsx << (2 * (len + 1)));
      nsnum += (nsy << (2 * (len - 1)));
      if (mp[nsnum] > 0) continue;
      mp[nsnum] = 1;
      que.push(pair<int, int>(nsnum, scnt + 1));
    }
  }
  cout << -1 << endl;
  return 0;
}
