A = "01234567"
memo = {A=>0}

stack = [[A, 0]]
table = [[1, 4], [0, 2, 5], [1, 3, 6], [2, 7],
         [0, 5], [4, 6, 1], [5, 7, 2], [3, 6]].freeze

while (board = stack.shift)
  swap = ->(a, b) {
    tmp = board.first.dup
    tmp[a], tmp[b] = tmp[b], tmp[a]
    [tmp, board.last]
  }
  i = board.first.index("0")
  table[i].each do |j|
    nxt = swap.(i, j)
    next if memo[nxt.first]
    nxt[1] += 1
    memo[nxt.first] = nxt.last
    stack << nxt
  end
end

$<.readlines.map {|a| a.split.join}.each do |given|
  puts memo[given]
end
