#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;

bool visited[10][10];

int main() {
  int h,w;
  while(cin>>w>>h,h||w) {
    string s;
    REP(i,h)REP(j,w) {
      char c;
      cin>>c;
      s += string(1,c);
    }
    
    typedef pair<string, int> psi;
    queue<psi> Q;
    Q.push(psi(s,0));
    int ans = -1;
    while(!Q.empty()) {
      psi p = Q.front(); Q.pop();
      string s = p.first;
      int d = p.second;

      // REP(i,h) {
      //   REP(j,w) cout << s[i*w+j];
      //   cout << endl;
      // }cout << endl;

      vector<pii> v;
      queue<pii> Q2;
      Q2.push(pii(0,0));
      memset(visited,0,sizeof(visited));
      visited[0][0] = 1;
      const int dy[] = {-1,0,1,0};
      const int dx[] = {0,1,0,-1};
      char col = s[0];
      set<char> st;
      while(!Q2.empty()) {
        pii q = Q2.front(); Q2.pop();
        v.push_back(q);
        REP(i,4) {
          int yy=q.first + dy[i];
          int xx=q.second+dx[i];
          if (yy<0||yy>=h||xx<0||xx>=w) continue;
          if (visited[yy][xx]) continue;
          if (s[yy*w+xx] == col) {
            visited[yy][xx] = 1;
            Q2.push(pii(yy,xx));
          } else {
            st.insert(s[yy*w+xx]);
          }
        }
      }
      if (st.size() == 0) {
        ans = d;
        break;
      }
      FOR(it, st) {
        FOR(jt, v) {
          s[jt->first*w+jt->second] = *it;
        }
        Q.push(psi(s,d+1));
      }
    }
    cout << ans << endl;
  }
  
}