DIRS=[ [[1,2],[2,1],[-1,2],[2,-1],[1,-2],[-2,1],[-1,-2],[-2,-1]], [[1,1],[-1,1],[1,-1],[-1,-1]] ] h,w=gets.split.map(&:to_i) rh=0...h rw=0...w board=h.times.map{gets.chomp} sx=sy=tx=ty=0 h.times{|i|w.times{|j| if board[i][j]==?S sx=i sy=j elsif board[i][j]==?G tx=i ty=j end }} q=[] s=[sx,sy,0] q.push s visited={} visited[s]=0 t1=[tx,ty,0] t2=[tx,ty,1] until q.empty?||visited[t1]||visited[t2] state=q.shift x,y,piece=state step=visited[state] DIRS[piece].each{|dx,dy| nx=x+dx ny=y+dy next unless rh===nx&&rw===ny np=board[nx][ny]==?R ? 1-piece : piece next_state=[nx,ny,np] next if visited[next_state] visited[next_state]=step+1 q.push next_state } end puts visited[t1]||visited[t2]||-1