### constant

INF = 1 << 30

C_E = 0
C_W = 1
C_R = 2
C_B = 3

CHASH = {'E' => C_E, 'W' => C_W, 'R' => C_R, 'B' => C_B}
CCUBE = [C_W, C_R, C_B]
ECUBE = [C_E, C_E, C_E]

MAX_D = 30

DXYS = [[1, 0], [0, 1], [-1, 0], [0, -1]]

### subroutines

def check_rec(d, x0, y0, pdi)
  return if d >= $gdist

  diff = (0...9).count{|i| $brd[i][0] != $gl[i]}
  if diff == 0
    $gdist = d if $gdist > d
    return
  end
  return if d + diff > $gdist

  pos0 = y0 * 3 + x0
  
  for di in (0...4)
    next if ((di + 2) % 4) == pdi
    dx, dy = DXYS[di]
    x = x0 + dx
    y = y0 + dy
    if x >= 0 && x < 3 && y >= 0 && y < 3
      pos = y * 3 + x
      pcb = $brd[pos]
      $brd[pos] = ECUBE
      cb = pcb.clone
      if dx != 0
        t = cb[0]; cb[0] = cb[2]; cb[2] = t
      else
        t = cb[0]; cb[0] = cb[1]; cb[1] = t
      end
      $brd[pos0] = cb

      check_rec(d + 1, x, y, di)

      $brd[pos] = pcb
      $brd[pos0] = ECUBE
    end
  end
end

### main

loop do
  sx, sy = gets.split.map(&:to_i)
  break if (sx | sy) == 0

  sx -= 1
  sy -= 1
  
  $gl = 3.times.map{gets.strip.split.map{|c| CHASH[c]}}.flatten
  #p $gl

  $brd = 9.times.map{CCUBE.clone}
  $brd[sy * 3 + sx] = ECUBE
  #p $brd

  $gdist = MAX_D + 1

  check_rec(0, sx, sy, -1)

  p ($gdist > MAX_D) ? -1 : $gdist
end