import std.stdio;
import std.functional;
import std.math;
import std.algorithm;
import std.string;
import std.typecons;

alias Tuple!(int, "y", int , "x") P;
int dist(P s, P t) {
    return abs(s.y - t.y) + abs(s.x - t.x);
}
int next(int c) {
    return (c + 1) % 5;
}
int prev(int c) {
    return (c + 5 - 1) % 5;
}

void main() {
    int X, Y; 
    string[] F;
    P s, g;
    P[][] cs;
    void init() {
        cs = new P[][5];
        foreach (i; 0 .. Y) {
            foreach (j; 0 .. X) {
                char c = F[i][j];
                if ('1' <= c && c <= '5') {
                    cs[c - '1'] ~= P(i, j);
                }
                if (c == 'S') {
                    s.y = i;
                    s.x = j;
                } 
                if (c == 'G') {
                    g.y = i;
                    g.x = j;
                }
            }
        }
    }
    int calc(int first) {
        int[P][] dp = new int[P][5];
        foreach (c; cs[first.next]) {
            dp[first.next][c] = dist(s, c);
        }
        for (int i = first.next.next; i != first; i = i.next) {
            int p = i.prev;
            foreach (c; cs[i]) {
                dp[i][c] = int.max / 2;
                foreach (q; cs[p]) {
                    dp[i][c] = min(dp[i][c], dp[p][q] + dist(c, q));
                }
            }
        }
        int last = first.prev;
        int ans = int.max / 2;
        foreach (c; cs[last]) {
            ans = min(ans, dp[last][c] + dist(c, g));
        }
        return ans;
    }
    while (readf("%d %d\n", &X, &Y), X || Y) {
        F = new string[Y];
        foreach (ref L; F) L = readln.chomp;
        init;
        int ans = int.max / 2;
        int first = 0;
        foreach (i; 0 .. 5) {
            int cand = calc(i);
            if (ans > cand) {
                ans = cand;
                first = i + 1;
            }
        }
        if (ans == int.max / 2) {
            "NA".writeln;
        } else {
            first.writeln(" ", ans);
        }
    }
}