#include <bits/stdc++.h>
using namespace std;
int n, m;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, m;
  cin >> n >> m;
  string a(n * m, n * m);
  char mx = '1';
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a[i * m + j];
      if (isdigit(a[i * m + j])) mx = max(mx, a[i * m + j]);
    }
  queue<string> q;
  map<string, int> mp;
  mp[a] = 0;
  q.push(a);
  long long lim = 1e5;
  long long ats = 666666666;
  while (!q.empty() && lim--) {
    string c = q.front();
    q.pop();
    int rr, cc;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        if (c[i * m + j] == '1') rr = i, cc = j;
    int dr[] = {-1, 1, 0, 0};
    int dc[] = {0, 0, -1, 1};
    queue<array<int, 2>> Q;
    vector<vector<int>> sp(16, vector<int>(16, 666));
    sp[rr][cc] = 0;
    Q.push({rr, cc});
    while (!Q.empty()) {
      int row = Q.front()[0];
      int col = Q.front()[1];
      Q.pop();
      for (int k = 0; k < 4; k++) {
        int R = row + dr[k];
        int C = col + dc[k];
        if (min(R, C) >= 0 && R < n && C < m &&
            (c[R * m + C] == '@' || c[R * m + C] == '.')) {
          if (c[R * m + C] == '@') {
            ats = min(ats, mp[c] + 1LL + sp[row][col]);
            continue;
          }
          if (sp[R][C] != 666) continue;
          sp[R][C] = sp[row][col] + 1;
          Q.push({R, C});
        }
      }
    }
    for (int k = 0; k < 4; k++) {
      int R = rr + dr[k];
      int C = cc + dc[k];
      if (min(R, C) >= 0 && R < n && C < m &&
          (c[R * m + C] == '@' || c[R * m + C] == '.' || c[R * m + C] == mx)) {
        string cp = c;
        if (c[R * m + C] == '@') return cout << mp[c] + 1, 0;
        for (int i = 0; i < n; i++)
          for (int j = 0; j < m; j++)
            if (isdigit(cp[i * m + j])) {
              cp[i * m + j]++;
              if (c[R * m + C] != mx && cp[i * m + j] > mx) cp[i * m + j] = '.';
            }
        cp[R * m + C] = '1';
        if (!mp.count(cp)) mp[cp] = mp[c] + 1, q.push(cp);
      }
    }
  }
  cout << (ats == 666666666 ? -1 : ats);
}
