
import qualified Data.Map as Map
import Data.Maybe

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 =
  let
    ls = kenkenpa3 map start
    next = head ls
  in
    if next == (-1) || next `elem` memo then (-1)
    else if next == dest then num
    else steps map 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 1

    
