#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cctype>
using namespace std;

const int INF = (int)1e9;

struct Node {
  int y, x, s;
  Node(int y_, int x_, int s_) : y(y_), x(x_), s(s_) { }
};

int main() {
  while(true) {
    int W, H; cin >> W >> H;
    if(W == 0 && H == 0) break;
    char F[H][W+1];
    for(int i = 0; i < H; ++i) {
      cin >> F[i];
    }
    int dp[H][W][1<<5];
    for(int i = 0; i < H; ++i)
      for(int j = 0; j < W; ++j)
        for(int k = 0; k < (1 << 5); ++k)
          dp[i][j][k] = INF;

    queue<Node> Q;
    for(int i = 0; i < H; ++i) {
      for(int j = 0; j < W; ++j) {
        if(F[i][j] == 'S') {
          for(int k = 0; k < 5; ++k) {
            dp[i][j][1 << k] = 0;
            Q.emplace(i, j, 1 << k);
          }
        }
      }
    }

    int ans = -1;

    while(!Q.empty()) {
      Node node = Q.front(); Q.pop();
      if(F[node.y][node.x] == 'G' && node.s == (1 << 5) - 1) {
        ans = dp[node.y][node.x][node.s];
        break;
      }

      for(int i = 0; i < 4; ++i) {
        static int dx[] = { 1, 0, -1, 0 };
        static int dy[] = { 0, -1, 0, 1 };
        int nx = node.x + dx[i];
        int ny = node.y + dy[i];
        if(nx < 0 || nx >= W || ny < 0 || ny >= H)
          continue;
        int nextScore = dp[node.y][node.x][node.s] + 1;
        if(dp[ny][nx][node.s] > nextScore) {
          dp[ny][nx][node.s] = nextScore;
          Q.emplace(ny, nx, node.s);
        }
        if(isdigit(F[ny][nx])) {
          int num = F[ny][nx] - '1';
          int S = node.s | (1 << num);
          if(dp[ny][nx][S] > nextScore) {
            dp[ny][nx][S] = nextScore;
            Q.emplace(ny, nx, S);
          }
        }
      }
    }

    if(ans == -1) {
      cout << "NA" << endl;
    }
    else {
      cout << ans << endl;
    }
  }
}