#include <bits/stdc++.h>
using namespace std;
int n, m;
int N;
struct hash_vc {
  size_t operator()(const vector<unsigned char>& x) const {
    int res = 0;
    for (int i = 0; i < N; ++i) {
      res <<= 2;
      res += x[i];
    }
    return res;
  }
};
void runCase(int caseNum) {
  int xstep[] = {1, 0, -1, 0};
  int ystep[] = {0, 1, 0, -1};
  cin >> n >> m;
  N = 0;
  vector<string> fd;
  for (int i = 0; i < n; ++i) {
    string s;
    cin >> s;
    fd.push_back(s);
    for (int j = 0; j < s.size(); ++j)
      if (s[j] > '0' && s[j] <= '9') N = max(N, s[j] - '0');
  }
  pair<vector<unsigned char>, int> start;
  start.first = vector<unsigned char>(N, 0);
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      if (fd[i][j] > '0' && fd[i][j] <= '9') {
        int pos = fd[i][j] - '0' - 1;
        start.first[pos] = (char)((i << 4) + j);
      }
    }
  }
  unordered_set<vector<unsigned char>, hash_vc> visited;
  queue<pair<vector<unsigned char>, int> > que;
  que.push(start);
  int res = (1 << 20);
  while (!que.empty()) {
    pair<vector<unsigned char>, int> cur = que.front();
    que.pop();
    if (visited.count(cur.first)) continue;
    visited.insert(cur.first);
    unsigned char p = cur.first[0];
    int curx = (p >> 4);
    int cury = (p & ((1 << 4) - 1));
    for (int i = 0; i < 4; ++i) {
      int nextx = curx + xstep[i];
      int nexty = cury + ystep[i];
      if (nextx >= n || nexty >= m || nextx < 0 || nexty < 0) continue;
      bool OK = true;
      if (fd[nextx][nexty] == '@') {
        res = cur.second + 1;
        break;
      } else if (fd[nextx][nexty] == '#')
        continue;
      unsigned char pp = (unsigned char)((nextx << 4) + nexty);
      for (int j = 1; j < N - 1; ++j)
        if (pp == cur.first[j]) {
          OK = false;
          break;
        }
      if (!OK) continue;
      pair<vector<unsigned char>, int> n(vector<unsigned char>(N, 0),
                                         cur.second + 1);
      n.first[0] = pp;
      for (int j = 0; j < N - 1; ++j) n.first[j + 1] = cur.first[j];
      if (visited.count(n.first)) continue;
      que.push(n);
    }
    if (res < (1 << 20)) break;
  }
  if (res > (1 << 15)) res = -1;
  cout << res << endl;
}
int main(int argc, char* argv[]) {
  runCase(0);
  return 0;
}
