
import qualified Data.Map as Map
import Data.Maybe
import qualified Control.Monad.State as St

newtype Env = Env { runEnv :: (Map.Map Int Int, Map.Map Int Int, Map.Map Int Int) }
  deriving (Eq,Show)

kenkenpa' :: Int -> St.State Env Int
kenkenpa' start = do
  env <- St.get
  let (m1,m2,m3) = runEnv env
  case Map.lookup start m1 of
    Nothing -> return (-1)
    Just r1 ->
      case Map.lookup r1 m2 of
        Nothing -> return (-1)
        Just r2 -> 
          case Map.lookup r2 m3 of
            Nothing -> return (-1)
            Just r3 ->
              case Map.lookup r3 m1 of
                Nothing -> return (-1)
                Just r0 -> do
                  St.put . Env $ (Map.delete start m1, Map.delete r1 m2, Map.delete r2 m3)
                  return r0

find :: Int -> Int -> Int -> St.State Env Int
find start dest num = do
  r <- kenkenpa' start
  if r == (-1) then return (-1)
  else if r == dest then return num
  else find r dest (num+1)


kenkenpa :: Map.Map Int Int -> Int -> [Int]
kenkenpa map start = (:[]) $ fromMaybe (-1) (Map.lookup start map)

kenkenpa3 :: Map.Map Int Int -> Int -> [Int]
kenkenpa3 map start = kenkenpa map start >>= kenkenpa map >>= kenkenpa map


steps :: Map.Map Int Int -> [Int] -> Int -> Int -> Int -> Int
steps map memo start dest num =
  if start == dest then num else
  let
    ls = kenkenpa3 map start
    next = head ls
  in
    if next == dest then num+1
    else if next == (-1) || next `elem` memo then (-1)
    else steps map (next:memo) next dest (num+1)

main = do
  _ <- getLine
  s <- map  ((\ls -> (head ls,last ls)) . map read . words) . lines <$> getContents :: IO [(Int,Int)]
  let map = Map.fromList (init s)
  let (start,dest) = last s
  -- print $ steps map [start] start dest 0
  print $ St.evalState (find start dest 1) (Env (map,map,map))

    
