#include <bits/stdc++.h>
using namespace std;
struct pe {
  char ta[20][20];
};
const int xx[] = {0, 1, 0, -1};
const int yy[] = {1, 0, -1, 0};
bool ketemu = false;
int dist[20][20][4];
int mins, n, m, apx, apy;
char maks;
pe arr;
bool ok(int x, int y) { return x >= 1 && x <= n && y >= 1 && y <= m; }
void dfs(pe x, int y) {
  int fx;
  int fy;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (x.ta[i][j] == '1') {
        fx = i;
        fy = j;
        break;
      }
  if (apx == fx && apy == fy) {
    if (!ketemu) {
      ketemu = true;
    }
    return;
  }
  for (int i = 0; i <= 3; i++)
    if (ok(fx + xx[i], fy + yy[i]) && y + 1 < dist[fx + xx[i]][fy + yy[i]][i] &&
        (x.ta[fx + xx[i]][fy + yy[i]] == '.' ||
         (x.ta[fx + xx[i]][fy + yy[i]] == maks && maks > '2') ||
         x.ta[fx + xx[i]][fy + yy[i]] == '@')) {
      pe tmp = x;
      tmp.ta[fx + xx[i]][fy + yy[i]] = '0';
      for (int j = 1; j <= n; j++)
        for (int k = 1; k <= m; k++) {
          if (tmp.ta[j][k] >= '0' && tmp.ta[j][k] <= '9') {
            tmp.ta[j][k]++;
            if (tmp.ta[j][k] > maks) tmp.ta[j][k] = '.';
          }
        }
      dist[fx + xx[i]][fy + yy[i]][i] = y + 1;
      dfs(tmp, y + 1);
    }
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      for (int k = 0; k <= 3; k++) dist[i][j][k] = 99999;
  int anux, anuy;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      cin >> arr.ta[i][j];
      if (arr.ta[i][j] == '@') {
        apx = i;
        apy = j;
      }
      if (arr.ta[i][j] == '1') {
        anux = i;
        anuy = j;
      }
      if (arr.ta[i][j] >= '1' && arr.ta[i][j] <= '9')
        maks = max(maks, arr.ta[i][j]);
    }
  dfs(arr, 0);
  if (ketemu) {
    mins =
        min(dist[apx][apy][0],
            min(dist[apx][apy][1], min(dist[apx][apy][2], dist[apx][apy][3])));
    printf("%d\n", mins);
  } else
    printf("-1\n");
}
