#include <bits/stdc++.h>
using namespace std;
char a[16][16];
int n, m, len;
const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
struct State {
  char b[16][16];
  int steps;
  int hash() {
    int p = 0;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) p = p * 171 + b[i][j];
    return p;
  }
  void takeout(char x) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++)
        if (b[i][j] == x) b[i][j] = '.';
    }
  }
  void increase() {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (isdigit(b[i][j])) b[i][j]++;
      }
    }
  }
};
queue<State> Q;
set<int> used;
int ans = -1;
bool checkpos(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
void Move(State &state) {
  state.steps++;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (state.b[i][j] == '2') {
        for (int f = 0; f < 4; f++) {
          int x = i + dx[f], y = j + dy[f];
          if (checkpos(x, y)) {
            if (state.b[x][y] == '@') {
              ans = state.steps;
              return;
            }
            if (state.b[x][y] == '.') {
              state.b[x][y] = '1';
              int h = state.hash();
              if (!used.count(h)) {
                Q.push(state);
                used.insert(h);
              }
              state.b[x][y] = '.';
            }
          }
        }
        return;
      }
    }
  }
}
int main() {
  int a1, b;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", a[i]);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] == '@') a1 = i, b = j;
      if (isdigit(a[i][j])) len = max(len, a[i][j] - '0');
    }
  }
  bool ok = 0;
  for (int i = 0; i < 4; i++) {
    int A = a1 + dx[i], B = b + dy[i];
    if (checkpos(A, B))
      if (a[A][B] != '#') ok = 1;
  }
  if (!ok) {
    printf("%s\n", "-1");
    return 0;
  }
  State init;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) init.b[i][j] = a[i][j];
  }
  init.steps = 0;
  used.insert(init.hash());
  Q.push(init);
  while (!Q.empty() && ans == -1) {
    State state = Q.front();
    Q.pop();
    state.takeout(len + '0');
    state.increase();
    Move(state);
  }
  printf("%d\n", ans);
  return 0;
}
