#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Info{
	char map[10][10];
};

struct Data{
	Data(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

int H,W;
int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};
char base_map[10][10];
bool FLG;

char to_color[3] = {'R','G','B'};

bool rangeCheck(int row,int col){
	if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true;
	else{
		return false;
	}
}

void back_track(Info info,int depth,int max_depth){

	if(FLG)return;

	if(depth == max_depth){
		bool is_cleared = true;
		for(int row = 0; row < H; row++){
			for(int col = 0; col < W; col++){
				if(info.map[row][col] != info.map[0][0]){
					is_cleared = false;
					break;
				}
			}
			if(!is_cleared)break;
		}

		if(is_cleared){
			FLG = true;
		}
		return;
	}

	char pre_color = info.map[0][0];

	queue<Data> Q;
	int adj_row,adj_col;

	for(int loop = 0; loop < 3; loop++){
		if(to_color[loop] == pre_color)continue;

		Info next_info;
		for(int row = 0;row < H; row++){
			for(int col = 0; col < W; col++){
				next_info.map[row][col] = info.map[row][col];
			}
		}

		next_info.map[0][0] = to_color[loop];

		Q.push(Data(0,0));

		while(!Q.empty()){

			for(int i = 0; i < 4; i++){
				adj_row = Q.front().row + diff_row[i];
				adj_col = Q.front().col + diff_col[i];

				if(!rangeCheck(adj_row,adj_col))continue;

				if(next_info.map[adj_row][adj_col] == pre_color){
					next_info.map[adj_row][adj_col] = to_color[loop];
					Q.push(Data(adj_row,adj_col));
				}
			}

			Q.pop();
		}
		if(depth < max_depth){
			back_track(next_info,depth+1,max_depth);
		}
	}
}

void func(){

	char buf[2];

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			scanf("%s",buf);
			base_map[row][col] = buf[0];
		}
	}

	FLG = false;
	int ans = 0;

	for(int i = 0; ; i++){
		Info info;

		for(int row = 0; row < H; row++){
			for(int col = 0; col < W; col++){
				info.map[row][col] = base_map[row][col];
			}
		}
		back_track(info,0,i);

		if(FLG){
			ans = i;
			break;
		}
	}

	printf("%d\n",ans);
}


int main(){

	while(true){
		scanf("%d %d",&W,&H);
		if(W == 0 && H == 0)break;

		func();
	}

	return 0;
}