import Control.Applicative ((<$>), (<*>))
import Control.Monad
import Data.List
import Data.Array.Unboxed
import Test.HUnit

main :: IO ()
-- main = runTestTT (TestList tests) >> return ()
main = do
  xs <- getc $ solve . split toInt
  mapM_ print xs

solve :: [Int] -> Int
solve xs = search 0 [] [((i `div` 4, i `mod` 4),listArray ((0,0),(1,3)) xs)]
  where
    i = maybe (-1) id (findIndex (== 0) xs)

goal :: ((Int,Int),UArray (Int,Int) Int)
goal = ((0,0),listArray ((0,0),(1,3)) [0..7])

move :: ((Int,Int),UArray (Int,Int) Int) -> [((Int,Int),UArray (Int,Int) Int)]
move ((i,j),arr) = [((ii,jj),arr // [((i,j),arr ! (ii,jj)),((ii,jj),0)]) | (ii,jj) <- [(i+1,j),(i-1,j),(i,j+1),(i,j-1)], ii >= 0, ii <= 1, jj >= 0, jj <= 3]

search :: Int -> [((Int,Int),UArray (Int,Int) Int)] -> [((Int,Int),UArray (Int,Int) Int)] -> Int
search n hs xs
  | goal `elem` xs = n
  | otherwise = search (n+1) (zs ++ hs) ys
    where
      ys = concatMap move xs
      zs = ys \\ hs

toInt :: String -> Int
toInt s = read s

split :: (String -> a) -> String -> [a]
split f = map f . words

getc :: (String -> a) -> IO [a]
getc f = map f . lines <$> getContents