#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <cstring>
#include <map>
using namespace std;

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

struct State {
    int dis;
    int x,y,turn;
    State(int x,int y,int turn,int dis) : x(x), y(y), turn(turn) , dis(dis) {;}
};

map<char,int> idx;
int memo[1<<8][30][30];

int bfs(vector<string> &mp) {
    const int h = mp.size();
    const int w = mp[0].length();

    int nx,ny,gx,gy;

    for(int i=0; i<(1<<8); ++i)
        for(int j=0; j<30; ++j)
            for(int k=0; k<30; ++k)
                memo[i][j][k] = -1;

    for(int i=0; i<h; ++i) {
        for(int j=0; j<w; ++j) {
            if(mp[i][j] == '@') {
                nx = j; ny = i;
                mp[i][j] = '.';
            } else if(mp[i][j] == '<') {
                gx = j; gy = i;
                mp[i][j] = '.';
            }
        }
    }

    queue<State> Q;
    Q.push(State(nx,ny,0,0));

    while(!Q.empty()) {
        State st = Q.front(); Q.pop();
        int x = st.x, y = st.y;
        if(x == gx && y == gy) return st.turn;

        if(memo[st.dis][x][y] != -1) continue;
        memo[st.dis][x][y] = st.turn;

        for(int dir = 0; dir<4; ++dir) {
            int nx = x + dx[dir], ny = y + dy[dir];
            if(nx < 0 || nx >= w || ny < 0 || ny > h-1 || mp[ny][nx] == '#')
                continue;
            if(isupper(mp[ny][nx]) && (st.dis>>(idx[mp[ny][nx]]))%2 == 0)
                continue;

            State ns(nx,ny,st.turn+1,st.dis);

            if(islower(mp[ny][nx])) {
                if(!(idx.find(toupper(mp[ny][nx])) == idx.end()))
                    ns.dis ^= (1<<idx[toupper(mp[ny][nx])]);

//                cout<<"new dis "<<ns.dis<<" push "<<idx[toupper(mp[ny][nx])]<<endl;
                Q.push(ns);
            }else{
                Q.push(ns);
            }
        }
    }

    return -1;
}

int main() {
    int W,H;
    while(cin>>W>>H, W|H) {
        idx.clear();
        vector<string> mp;
        string s;
        for(int i=0; i<H; ++i) {
            cin>>s;
            mp.push_back(s);
        }

        int nc = 0;
        for(int i=0; i<H; ++i)
            for(int j=0; j<mp[i].length(); ++j)
                if(isupper(mp[i][j]) && idx.find(mp[i][j]) == idx.end())
                    idx[mp[i][j]] = nc++;


        cout<<bfs(mp)<<endl;
    }
}