### subroutines

def paint(c, brd)
  corg = brd[0]
  return brd if corg == c

  brd0 = brd.clone
  brd0[0] = c
  q = [[0, 0]]

  while ! q.empty?
    x, y = q.shift

    if x < $w - 1
      id0 = y * $w + (x + 1)
      if brd0[id0] == corg
        brd0[id0] = c
        q << [x + 1, y]
      end
    end

    if y < $h - 1
      id1 = (y + 1) * $w + x
      if brd0[id1] == corg
        brd0[id1] = c
        q << [x, y + 1]
      end
    end
  end

  brd0
end

### main

while true
  $w, $h = gets.strip.split(' ').map{|s| s.to_i}
  break if $w == 0 && $h == 0

  start = ''
  $h.times do
    start += gets.strip.split(' ').join('')
  end
  #p start

  goals = ['R', 'G', 'B'].map{|c| c * $w * $h}
  #p goals

  dists = {}
  dists[start] = 0
  q = [start]

  min_dist = nil

  while ! q.empty?
    u = q.shift

    if goals.include? u
      min_dist = dists[u]
      break
    end

    for v in ['R', 'G', 'B'].map{|c| paint(c, u)}
      if dists[v].nil?
        dists[v] = dists[u] + 1
        q << v
      end
    end
  end

  puts min_dist
end