#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {1, -1, 0, 0};
const int dy[4] = {0, 0, 1, -1};
int mod = 0, n, m, len = 3, stx, sty, cur = 0, finx, finy,
    step[1 << 16][20][20];
bool c[20][20];
char grid[20][20];
queue<pair<pair<int, int>, int> > q;
inline bool val(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
inline int getmask(int x, int y, char seek) {
  for (int i = 0; i < 4; i++) {
    int xx = x + dx[i], yy = y + dy[i];
    if (val(xx, yy) && grid[xx][yy] == seek)
      return (getmask(xx, yy, seek + 1) << 2) | i;
  }
  return 0;
}
inline int trim(int x) { return x & ((1 << (len - 2) * 2) - 1); }
inline void unrap(int x, int y, int mask, bool cc) {
  int d = len - 2;
  while (d--) {
    int g = mask & 3;
    mask >>= 2;
    x += dx[g], y += dy[g];
    c[x][y] = cc;
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> grid[i][j];
      if (isdigit(grid[i][j])) {
        int yy = (int)(grid[i][j] - '0');
        len = max(len, yy);
        if (yy == 1) stx = i, sty = j;
      }
      if (grid[i][j] == '@') finx = i, finy = j;
    }
  cur = trim(getmask(stx, sty, '2'));
  memset(step, 0, sizeof(step));
  memset(c, false, sizeof(c));
  q.push(make_pair(make_pair(stx, sty), cur));
  step[cur][stx][sty] = 1;
  while (!q.empty()) {
    int x = q.front().first.first, y = q.front().first.second,
        curPos = q.front().second;
    q.pop();
    unrap(x, y, curPos, true);
    if (x == finx && y == finy) {
      cout << step[curPos][x][y] - 1;
      return 0;
    }
    for (int i = 0; i < 4; i++) {
      int xx = x + dx[i], yy = y + dy[i], ooc = trim(curPos << 2 | (i ^ 1));
      if (val(xx, yy) && !c[xx][yy] && grid[xx][yy] != '#' &&
          step[ooc][xx][yy] == 0) {
        step[ooc][xx][yy] = step[curPos][x][y] + 1;
        q.push(make_pair(make_pair(xx, yy), ooc));
      }
    }
    unrap(x, y, curPos, false);
  }
  cout << -1 << endl;
  return 0;
}
