### constants

MAX_D = 20

### global variables

$min_dist = MAX_D
$goals = []

### 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

def min_dist(d, u, visited)
  if $goals.include? u
    $min_dist = d if $min_dist > d
    return
  end

  return if d >= $min_dist

  for v in ['R', 'G', 'B'].map{|c| paint(c, u)}
    if visited[v].nil?
      visited[v] = true
      min_dist(d + 1, v, visited)
      visited.delete(v)
    end
  end
end

### main

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

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

  $goals = ['R', 'G', 'B'].map{|c| c * $wh}
  $min_dist = MAX_D

  min_dist(0, start, {start => true})

  puts $min_dist
end