#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;

struct P {
  int y, x, S;
  P(int y, int x, int S) : x(x), y(y), S(S) {}
};
char ba[30][30];
int rock[30][30];
int dist[30][30][1<<8];

int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};

int main() {
  int w,h;
  while(cin>>w>>h,w||h) {
    queue<P> Q;
    memset(dist,-1,sizeof(dist));
    int rocknum = 0;
    memset(rock, -1, sizeof(rock));
    map<char, int> mp;
    REP(i, h) {
      REP(j, w) {
        cin >> ba[i][j];
        if (ba[i][j] == '@') {
          dist[i][j][0] = 0;
          Q.push(P(i,j,0));
        }
        if (isupper(ba[i][j])) {
          if (mp.count(ba[i][j]) == 0) mp[ba[i][j]] = rocknum++;
        }
      }
    }
    int ans = -1;
    while(!Q.empty()) {
      P p = Q.front(); Q.pop();
      //cout << p.y << " " << p.x << " " << p.S << endl;
      //if (dist[p.y][p.x][p.S]>=0) continue;
      if (ba[p.y][p.x] == '<') {
        ans = dist[p.y][p.x][p.S];
        break;
      }
      REP(i, 4) {
        int yy = p.y+dy[i];
        int xx = p.x+dx[i];
        if (yy<0||yy>=h||xx<0||xx>=w) continue;
        if (ba[yy][xx] == '#') continue;
        
        int nS = p.S;
        if (islower(ba[yy][xx])) {
          char c = toupper(ba[yy][xx]);
          if (mp.count(c)) {
            nS ^= 1<<mp[c];
          }
        } else if (isupper(ba[yy][xx])) {
          if (!(nS >> mp[ba[yy][xx]] & 1)) continue;
        }
        //cout << yy  << ":" << xx << ":" << nS << " " << dist[yy][xx][nS] << endl;
        if (dist[yy][xx][nS] == -1) {
          dist[yy][xx][nS] = dist[p.y][p.x][p.S] + 1;
          Q.push(P(yy,xx,nS));
        }
      }
    }
    cout << ans << endl;
  }
}