#include <bits/stdc++.h>
using namespace std;

typedef pair<int, string> P;

const char rgb[] = "RGB";
const int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};

int x, y;

bool check(string& s)
{
    char start = s[0];
    for (char c : s){
        if (c != start) return false;
    }
    return true;
}

void change(string& s, int cx, int cy, char from, char to)
{
    if (cx < 0 || x <= cx || cy < 0 || y <= cy || s[cy * x + cx] != from) return;
    s[cy * x + cx] = to;
    for (int i = 0; i < 4; i++){
        change(s, cx + dx[i], cy + dy[i], from, to);
    }
}

int main()
{
    while (scanf("%d %d", &x, &y), x){
        char grid[128] = {0};
        for (int i = 0; i < x * y; i++){
            scanf(" %c", grid + i);
        }

        string s(grid);
        set<string> exist;
        queue<P> que;
        for (exist.insert(s), que.push(P(0, s)); ; que.pop()){
            P p = que.front();

            if (check(p.second)){
                printf("%d\n", p.first);
                break;
            }

            for (char c : rgb){
                string tmp = p.second;

                if (tmp[0] != c){
                    change(tmp, 0, 0, tmp[0], c);
                    if (exist.find(tmp) == exist.end()){
                        exist.insert(tmp);
                        que.push(P(p.first + 1, tmp));
                    }
                }
            }
        }
    }

    return 0;
}