import Control.Monad

solve :: Int -> Int -> Int -> [(Int, Int)] -> Int
solve count index n as
  | button == 2 = count
  | count > n = -1
  | otherwise = solve (count + 1) (button - 1) n as
  where (_, button) = as !! index

main :: IO ()
main = do
  n <- readLn
  as <- replicateM n readLn :: IO [Int]
  print . solve 1 0 n $ zip [1..] as