#include <bits/stdc++.h>
using namespace std;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int n, m, l = 0;
int sum = 0;
string a[20];
int v[20][20];
struct point {
  int x;
  int y;
} snake[10];
struct node {
  int x;
  int y;
  int d;
  point s[10];
};
int bfs(int x, int y) {
  queue<node> q;
  v[x][y]++;
  node fir;
  fir.x = x;
  fir.y = y;
  fir.d = 0;
  for (int i = 1; i <= l; i++) fir.s[i] = snake[i];
  q.push(fir);
  while (!q.empty()) {
    node f = q.front();
    q.pop();
    sum++;
    if (sum > n * m * 100) return -1;
    v[f.x][f.y]--;
    for (int i = 0; i < 4; i++) {
      node next;
      next.x = f.x + dx[i];
      next.y = f.y + dy[i];
      if (next.x < 0 || next.x >= n || next.y < 0 || next.y >= m) continue;
      if (a[next.x][next.y] == '#' || v[next.x][next.y] >= 2) continue;
      if (a[next.x][next.y] == '@') return f.d + 1;
      bool flag = true;
      for (int i = 2; i < l; i++)
        if (next.x == f.s[i].x && next.y == f.s[i].y) {
          flag = false;
          break;
        }
      if (!flag) continue;
      next.d = f.d + 1;
      for (int i = 1; i < l; i++) next.s[i + 1] = f.s[i];
      next.s[1].x = next.x;
      next.s[1].y = next.y;
      v[next.x][next.y]++;
      q.push(next);
    }
  }
  return -1;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    for (int j = 0; j < m; j++) {
      if (a[i][j] > '0' && a[i][j] <= '9') {
        int t = a[i][j] - '0';
        l = max(l, t);
        snake[t].x = i;
        snake[t].y = j;
        a[i][j] = '.';
      }
    }
  }
  memset(v, 0, sizeof(v));
  int ans = bfs(snake[1].x, snake[1].y);
  if (ans < 0)
    printf("-1\n");
  else
    printf("%d\n", ans);
  return 0;
}
