#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};
const int maxn = 17, maxt = 70007;
int n, m, K, S;
int pow4[maxn];
char Map[maxn][maxn];
bool use[maxn][maxn][maxt], can[maxn][maxn];
int dist[maxn][maxn][maxt];
bool check_map(int x, int y) {
  if (x < 0 || x >= n) return false;
  if (y < 0 || y >= m) return false;
  return true;
}
void dfs(int x, int y, int dep, int sum) {
  K = dep, S = sum;
  for (int i = 0; i < 4; i++) {
    int xx = x + dx[i], yy = y + dy[i];
    if (check_map(xx, yy) && Map[xx][yy] == Map[x][y] + 1)
      dfs(xx, yy, dep + 1, sum * 4 + i);
  }
}
struct ZZ {
  int x, y, s;
  ZZ() {}
  ZZ(int _x, int _y, int _s) { x = _x, y = _y, s = _s; }
};
void getMap(int X, int Y, int S) {
  memset(can, true, sizeof(can));
  int a[maxn];
  for (int i = 1; i <= K; i++) a[i] = S % 4, S /= 4;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (Map[i][j] == '#') can[i][j] = false;
  for (int x = X, y = Y, run = K; run > 0;
       x += dx[a[run]], y += dy[a[run]], run--)
    can[x][y] = false;
}
int bfs(int X, int Y, int S) {
  queue<ZZ> zz;
  zz.push(ZZ(X, Y, S));
  use[X][Y][S] = true;
  dist[X][Y][S] = 0;
  while (zz.size()) {
    int x = zz.front().x, y = zz.front().y, s = zz.front().s;
    if (Map[x][y] == '@') return dist[x][y][s];
    zz.pop();
    getMap(x, y, s);
    for (int i = 0; i < 4; i++) {
      int xx = x + dx[i], yy = y + dy[i], ss = s / 4 + (i ^ 1) * pow4[K - 1];
      if (check_map(xx, yy) && can[xx][yy] && !use[xx][yy][ss]) {
        use[xx][yy][ss] = true;
        dist[xx][yy][ss] = dist[x][y][s] + 1;
        zz.push(ZZ(xx, yy, ss));
      }
    }
  }
  return -1;
}
int main() {
  pow4[0] = 1;
  for (int i = 1; i <= 10; i++) pow4[i] = pow4[i - 1] * 4;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", Map[i]);
  for (int x = 0; x < n; x++)
    for (int y = 0; y < m; y++)
      if (Map[x][y] == '1') {
        dfs(x, y, 0, 0);
        int res = bfs(x, y, S);
        printf("%d\n", res);
      }
  return 0;
}
