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

def swap(str, a, b)
  tmp = str.dup
  tmp[a], tmp[b] = tmp[b], tmp[a]
  tmp
end

def haba_search(answer, queue)
  loop do
    move_num, search = queue.shift
    break unless search

    a = search.index('0')
    MOVE_LIST[a].each do |b|
      next_str = swap(search, a, b)
      next if answer[next_str]
      answer[next_str] = move_num + 1
      queue.push([move_num + 1, next_str])
    end
  end
  answer
end

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

while str = gets
  str = str.chomp.gsub(' ', '')
  break if str.length <= 7
  puts answers[str]
end