#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int n, m, d;
queue<vector<int> > q;
map<vector<int>, int> mp;
bool visit[N][N];
char c[N][N];
inline bool ok(int x2, int y2) {
  return (x2 >= 0 && y2 >= 0 && x2 < n && y2 < m);
}
void dfs(int x, int y) {
  if (c[x][y] == '#' || !ok(x, y) || visit[x][y]) return;
  visit[x][y] = true;
  for (int i = 0; i < 4; i++) {
    int x2 = dx[i] + x;
    int y2 = dy[i] + y;
    dfs(x2, y2);
  }
}
int main() {
  cin >> n >> m;
  vector<int> v;
  for (int i = 0; i < n; i++) cin >> c[i];
  for (char i = '1'; i <= '9'; i++) {
    bool found = false;
    for (int j = 0; j < n; j++) {
      for (int l = 0; l < m; l++) {
        if (c[j][l] == i) {
          v.push_back(j);
          v.push_back(l);
          found = true;
        }
      }
    }
    if (!found) break;
  }
  dfs(v[0], v[1]);
  bool can = false;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (c[i][j] == '@' && visit[i][j]) {
        can = true;
        break;
      }
    }
    if (can) break;
  }
  if (!can) {
    cout << -1;
    return 0;
  }
  mp[v] = 0;
  q.push(v);
  while (!q.empty()) {
    v = q.front();
    q.pop();
    d = mp[v];
    for (int i = 0; i < 4; i++) {
      int x2 = v[0] + dx[i];
      int y2 = v[1] + dy[i];
      if (!ok(x2, y2) || c[x2][y2] == '#') continue;
      bool eat = false;
      for (int j = 0; j < v.size() / 2 - 1; j++)
        if (x2 == v[j * 2] && y2 == v[j * 2 + 1]) eat = true;
      if (eat) continue;
      if (c[x2][y2] == '@') {
        cout << d + 1 << endl;
        return 0;
      }
      vector<int> e(v.size());
      e[0] = x2;
      e[1] = y2;
      for (int j = 0; j < v.size() - 4; j++) e[2 + j] = v[j];
      if (mp.find(e) == mp.end()) {
        mp[e] = d + 1;
        q.push(e);
      }
    }
  }
  cout << -1;
  return 0;
}
