#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
int x,y;
int gx,gy;
char fie[1005][1005];
char che[1005][1005];

typedef struct state{
  int x;
  int y;
  int cost;
  int ty;
  //0...なし
  //1...1炎
  //2...2氷
  //4...3木
  //8...4土
  //16..5水
  state(int x,int y,int cost,int ty):x(x),y(y),cost(cost),ty(ty){}
}st;

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

int check(int nx,int ny,int ty){
  if(fie[nx][ny]=='1' && (ty&16) && !(ty&1) ) return 1;
  else if( fie[nx][ny]=='2' && (ty&1) && !(ty&2) ) return 2;
  else if( fie[nx][ny]=='3' && (ty&2) && !(ty&4) ) return 4;
  else if( fie[nx][ny]=='4' && (ty&4) && !(ty&8) ) return 8;
  else if( fie[nx][ny]=='5' && (ty&8) && !(ty&16) ) return 16;
  else if( fie[nx][ny]=='G' && (ty&31)) return 32;
  return 0;
}

int solve(int nx,int ny,int ty){
  queue <st> q;
  q.push( state(nx,ny,0,ty) );
  while(!q.empty()){
    st p = q.front(); q.pop();
    //    printf("%d %d %d %c\n",p.x,p.y,p.ty,fie[p.x][p.y]);
    for(int i=0;i<4;i++){
      int mx=p.x+dx[i];
      int my=p.y+dy[i];
      int mt=p.ty;
      if(mx < 0 || mx >= x || my < 0 || my >= y) continue;
      if(che[mx][my]!=-1) continue;
      //      printf("mt:%d + ch:%d\n",mt,check(mx,my,mt));
      mt += check(mx,my,mt);
      //      printf("mt.%d\n",mt);
      if(mt>=32) return p.cost+1;
      if(mt!=p.ty){
	memset(che,-1,sizeof(che));
	while(q.empty()) q.pop();
      }
      che[mx][my]=p.cost+1;
      q.push( state(mx,my,p.cost+1,mt) );
    }
  }
  return 0;
}

main(){
  while(1){
    int f[7]={0};
    int sx,sy;
    scanf("%d %d",&x,&y);
    if(!x && !y) break;
    memset(che,-1,sizeof(che));
    for(int i=0;i<y;i++){
      for(int j=0;j<x;j++){
      cin >> fie[j][i];
      if(fie[j][i]=='.') continue;
      if(fie[j][i]=='S'){ sx=j; sy=i;}
      else if(fie[j][i]=='G'){ gx=j; gy=i;}
      else f[fie[j][i]-'0']=1;
      }
    }
    for(int i=1;i<=5;i++){
      if(f[i]==0){ printf("NA\n"); f[0]=-1; break; }
    }
    if(f[0]==-1) continue;
    int res=( 1<<20 );
    for(int i=1;i<=16;i+=i){
      memset(che,-1,sizeof(che));
      res=min(res,solve(sx,sy,i));
    }
    printf("%d\n",res);
  }

}