MOVE_LIST = [
    [1,4],
    [0,2,5],
    [1,3,6],
    [2,7],
    [0,5],
    [1,4,6],
    [2,5,7],
    [3,6]
]

def swap(figure, n, m)
  tmp = figure.dup
  tmp[n], tmp[m] = tmp[m], tmp[n]
  tmp
end

def width_search(answers, queue)
  loop do
    move_num, figure = queue.shift
    break unless figure

    current_idx = figure.index('0')
    MOVE_LIST[current_idx].each do |new_idx|
      new_figure = swap(figure, current_idx, new_idx)
      next if answers[new_figure]
      answers[new_figure] = move_num + 1
      queue << [move_num + 1, new_figure]
    end
  end
  answers
end

goal = '01234567'
answers = { goal => 0 }
queue = [[0, goal]]
answers = width_search(answers, queue)

loop do
  str = gets.to_s.chomp.split(' ').map(&:to_i).join('')
  break if str.size == 0
  puts answers[str]
end