n=int(input())
k=[]
i=1
cnt=1
for i in range(n):
    l=int(input())
    k.append(l)
if k.count(2)==0:
    print(-1)
else:
    while i != 2 and cnt<=n:
        cnt += 1
        i=k[i-1]
    if i==2:
        print(cnt+1)
    else:
        print(-1)


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        BTrained solver = new BTrained();
        solver.solve(1, in, out);
        out.close();
    }

    static class BTrained {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int[] a = in.readIntArray(n);
            ArrayUtils.decreaseByOne(a);
            boolean[] visited = new boolean[n];
            int ans = 0;
            int pos = 0;
            while (true) {
                visited[pos] = true;
                pos = a[pos];
                ans++;
                if (pos == 1) {
                    out.printLine(ans);
                    return;
                }
                if (visited[pos]) {
                    out.printLine(-1);
                    return;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int[] readIntArray(int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = readInt();
            }
            return array;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }

    static class ArrayUtils {
        public static void decreaseByOne(int[] array) {
            int n = array.length;
            for (int i = 0; i < n; i++) {
                array[i]--;
            }
        }

    }
}


import java.io.*;
import java.util.*;

public class Main {
	static void solve() {
		int n = ni();
		int a[] = na(n);
		for(int i=0;i<n;i++)a[i]--;
		int cnt = 0;
		int now = 0;
		boolean used[] = new boolean[n];
		while(true) {
			if(now == 1) {
				out.println(cnt);
				return;
			}
			if(used[now]) {
				out.println(-1);
				return;
			}
			used[now] = true;
			cnt++;
			now = a[now];
		}
	}

	//constant
	static final long mod = (long) 1e9 + 7;
	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
	static final int inf = Integer.MAX_VALUE / 2;
	static final long linf = Long.MAX_VALUE / 3;
	static final double dinf = Double.MAX_VALUE / 3;
	static final double eps = 1e-10;
	static final double pi = Math.PI;
	static StringBuilder sb = new StringBuilder();
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	//libraries
	static void reverse(int ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(long ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(double ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(char ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static String getReverse(String s) {
		char c[] = s.toCharArray();
		reverse(c);
		s = String.valueOf(c);
		return s;
	}

	static <T> void reverse(List<T> ls) {
		int sz = ls.size();
		for (int i = 0; i < sz / 2; i++) {
			T t = ls.get(i);
			ls.set(i, ls.get(sz - 1 - i));
			ls.set(sz - 1 - i, t);
		}
	}

	static <T> void reverse(T[] ar) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			T t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void sbnl() {//StringBuilderに改行文字をappendする
		sb.append("\n");
	}

	static int lowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static <T> int lowerBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) >= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int upperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) > 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rupperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) < 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rlowerBound(List<T> ls, T x) {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) <= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static int[] concat(int x, int arr[]) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static int[] concat(int arr[], int x) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static long[] concat(long x, long arr[]) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static long[] concat(long arr[], long x) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static int max(int x, int y) {
		return Math.max(x, y);
	}

	static int min(int x, int y) {
		return Math.min(x, y);
	}

	static int max(int x, int y, int z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static int min(int x, int y, int z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static long max(long x, long y) {
		return Math.max(x, y);
	}

	static long min(long x, long y) {
		return Math.min(x, y);
	}

	static long max(long x, long y, long z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static long min(long x, long y, long z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static double max(double x, double y) {
		return Math.max(x, y);
	}

	static double min(double x, double y) {
		return Math.min(x, y);
	}

	static double max(double x, double y, double z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static double min(double x, double y, double z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static void sort(int[] ar) {
		Arrays.sort(ar);
	}

	static void sort(long[] ar) {
		Arrays.sort(ar);
	}

	static void sort(double[] ar) {
		Arrays.sort(ar);
	}

	static void sort(char[] ar) {
		Arrays.sort(ar);
	}

	static void rsort(int[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(long[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(double[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(char[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void fill(int arr[], int x) {
		Arrays.fill(arr, x);
	}

	static void fill(long arr[], long x) {
		Arrays.fill(arr, x);
	}

	static void fill(boolean arr[], boolean x) {
		Arrays.fill(arr, x);
	}

	static void fill(double arr[], double x) {
		Arrays.fill(arr, x);
	}

	static void fill(int arr[][], int x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(long arr[][], long x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(double arr[][], double x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(boolean arr[][], boolean x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	//MOD culc
	static long plus(long x, long y) {
		long res = (x + y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long sub(long x, long y) {
		long res = (x - y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long mul(long x, long y) {
		long res = (x * y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long div(long x, long y) {
		long res = x * pow(y, mod - 2) % mod;
		return res < 0 ? res + mod : res;
	}

	static long pow(long x, long y) {
		if (y < 0)
			return 0;
		if (y == 0)
			return 1;
		if (y % 2 == 1)
			return (x * pow(x, y - 1)) % mod;
		long root = pow(x, y / 2);
		return root * root % mod;
	}

	public static void main(String[] args) throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		solve();
		out.flush();
	}

	//input
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;

	private static int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private static boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private static int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	@SuppressWarnings("unused")
	private static double nd() {
		return Double.parseDouble(ns());
	}

	@SuppressWarnings("unused")
	private static char nc() {
		return (char) skip();
	}

	private static String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private static char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	@SuppressWarnings("unused")
	private static char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	@SuppressWarnings("unused")
	private static int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	@SuppressWarnings("unused")
	private static long[] nla(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}

	private static int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	@SuppressWarnings("unused")
	private static long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String[] args) throws IOException {
		InputReader in = new InputReader(System.in);
		int n = in.readInt();
		int arr[] = new int[n];

		for(int i = 0; i<n; i++) {
			arr[i] = in.readInt()-1;
		}
		int count = 0;
		int ans = 0;
        while(true) {
        	if(ans == 1) {
        	  System.out.println(count);
        	  return;
        	}
            if(count > n) {
            	System.out.println(-1);
            	return ;
            }
            ans = arr[ans];
            count++;
        }
	}
}
class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public long readLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public String next() {
		return readString();
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}


	import java.util.*;
	import java.io.*;

	public class Main{
		public static void main(String[] args)  throws IOException,NumberFormatException{
			try {
			FastScanner sc=new FastScanner();
			int n=sc.nextInt();
			int a[]=sc.readArray(n);
			boolean ans[]=new boolean[n];
			ans[0]=true;
			int count=0;
			for(int i=0;i<a.length;i++) {
				if(ans[i]==true) {
					ans[i]=false;
					ans[a[i]-1]=true;
					count++;
					if(ans[1]==true) {
						break;
					}
				}
			}

			if(ans[1]==false) {
				System.out.println("-1");
			}
			else {
				System.out.println(count);
			}
			}
			catch(Exception e) {
				return ;
			}

		}
		static final Random random=new Random();

		static void ruffleSort(int[] a) {
			int n=a.length;
			for(int i=0;i<n;i++) {
				int oi=random.nextInt(n),temp=a[oi];
				a[oi]=a[i]; a[i]=temp;
			}
			Arrays.sort(a);
		}

		public static class FastScanner {
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st=new StringTokenizer("");
			String next() {
				while (!st.hasMoreTokens())
					try {
	                                      st=new StringTokenizer(br.readLine());
	                              } catch (IOException e) {}
				return st.nextToken();
			}

			int nextInt() {
				return Integer.parseInt(next());
			}

			long nextLong() {
				return Long.parseLong(next());
			}

			int[] readArray(int n) {
				int[] a=new int[n];
				for (int i=0; i<n; i++) a[i]=nextInt();
				return a;
			}

			long[] readLongArray(int n) {
				long[] a=new long[n];
				for(int i=0; i<n ; i++) a[i]=nextLong();
				return a;
			}

			String nextLine()
	        {
	            String str = "";
	            try
	            {
	                str = br.readLine();
	            }
	            catch (IOException e)
	            {
	                e.printStackTrace();
	            }
	            return str;
	        }
		}

	}


	import java.util.*;
	import java.io.*;

	public class Main{
		public static void main(String[] args)  throws IOException,NumberFormatException{
			try {
			FastScanner sc=new FastScanner();
			int n=sc.nextInt();
			int a[]=sc.readArray(n);
			boolean ans[]=new boolean[n];
			ans[0]=true;
			int count=0;
			for(int i=0;i<a.length;i++) {
				if(ans[i]==true) {
					count++;
					ans[a[i]-1]=true;
					if(ans[1]==true) {
						break;
					}
				}
			}
			boolean sol=false;
			if(ans[1]==false) {
				System.out.println("-1");
			}
			else {
				System.out.println(count);
			}
			}
			catch(Exception e) {
				return ;
			}

		}
		static final Random random=new Random();

		static void ruffleSort(int[] a) {
			int n=a.length;
			for(int i=0;i<n;i++) {
				int oi=random.nextInt(n),temp=a[oi];
				a[oi]=a[i]; a[i]=temp;
			}
			Arrays.sort(a);
		}

		public static class FastScanner {
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st=new StringTokenizer("");
			String next() {
				while (!st.hasMoreTokens())
					try {
	                                      st=new StringTokenizer(br.readLine());
	                              } catch (IOException e) {}
				return st.nextToken();
			}

			int nextInt() {
				return Integer.parseInt(next());
			}

			long nextLong() {
				return Long.parseLong(next());
			}

			int[] readArray(int n) {
				int[] a=new int[n];
				for (int i=0; i<n; i++) a[i]=nextInt();
				return a;
			}

			long[] readLongArray(int n) {
				long[] a=new long[n];
				for(int i=0; i<n ; i++) a[i]=nextLong();
				return a;
			}

			String nextLine()
	        {
	            String str = "";
	            try
	            {
	                str = br.readLine();
	            }
	            catch (IOException e)
	            {
	                e.printStackTrace();
	            }
	            return str;
	        }
		}

	}


import java.util.*;
// warm-up
// pushing buttons..
public class Main {

	static void solve() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt(), i = 1, no = N, t = 1, j = 1;
		boolean ok = false;
		int[] a = new int[N+1];
		while (N-->0) a[i++] = sc.nextInt();
		while (no-->0) {
			j = a[j]; t++;
			if (a[j]==2) { ok = true; break; }
		}
		System.out.println(ok ? t : -1);
		sc.close();
	}

	public static void main(String args[]) {
		solve();
	}

}


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
//#include<algorithm>
//#include<vector>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint();
	int A[100001];
	rep1(i, N) A[i] = getint();
	bool iketa = 0;
	int ima = A[1];
	A[1] = 0;
	int kazu = 1;
	while (ima) {
		if (ima == 2) {
			iketa = 1;
			break;
		}
		int k = A[ima];
		A[ima] = 0;
		ima = k;
		kazu++;
	}

	if (iketa) printf("%d", kazu);
	else printf("-1");

	Would you please return 0;
}


#include <bits/stdc++.h>

class kin{
public:
	inline void open(FILE *,int);
	inline void close(void);
	inline void scan(void);
	inline kin &operator>(char &);
	inline kin &operator>(int &);
	inline kin &operator>(long long &);
	inline kin &operator>(double &);
	inline kin &operator>(long double &);
	inline kin &operator>(char *);
	template <class T> inline void get(T *,int);
private:
	FILE *fp;
	char *buf;
	int siz;
	int idx;
}in;

class kout{
public:
	inline void open(FILE *,int);
	inline void close(void);
	inline void print(void);
	inline kout &operator<(char);
	inline kout &operator<(int);
	inline kout &operator<(long long);
	inline kout &operator<(double);
	inline kout &operator<(long double);
	inline kout &operator<(const char *);
	template <class T> inline void put(T *,int,char,char);
private:
	FILE *fp;
	char *buf;
	int siz;
	int idx;
}out;

inline int gcd(int x,int y){
	if(x<y) std::swap(x,y);
	int r=x%y;
	while(r){
		x=y;
		y=r;
		r=x%y;
	}
	return y;
}

int main(int argc,char **argv){
	in.open(stdin,512);
	out.open(stdout,512);
	in.scan();
	int n;
	in>n;
	int a[100001];
	in.get(a+1,n);
	int d[100001];
	for(int i=1;i<=n;++i) d[i]=0;
	int p=1,ans=0;
	while(!d[p]){
		d[p]=1;
		++ans;
		p=a[p];
		if(p==2) break;
	}
	out<(p==2?ans:-1)<'\n';
	out.print();
	in.close();
	out.close();
	return 0;
}

inline void kin::open(FILE *fpa,int siza){
	fp=fpa;
	buf=new char[siza];
	siz=siza;
	idx=0;
	return;
}
inline void kin::close(void){
	fp=nullptr;
	delete[] buf;
	buf=nullptr;
	siz=0;
	idx=0;
	return;
}
inline void kin::scan(void){
	int readsiz=(int)std::fread((void *)buf,(std::size_t)1,(std::size_t)siz,fp);
	if(readsiz!=siz) buf[readsiz]='\x00';
	idx=0;
	return;
}
inline kin &kin::operator>(char &var){
	if(!buf[idx]){
		var='\x00';
		return *this;
	}
	var=buf[idx];
	if(++idx==siz) scan();
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(int &var){
	if(!buf[idx]){
		var=0;
		return *this;
	}
	int sign=-1;
	if(buf[idx]=='-'){
		sign=1;
		if(++idx==siz) scan();
	}
	var=0;
	while(buf[idx]>='0'){
		var=var*10-(int)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(long long &var){
	if(!buf[idx]){
		var=0LL;
		return *this;
	}
	long long sign=-1LL;
	if(buf[idx]=='-'){
		sign=1LL;
		if(++idx==siz) scan();
	}
	var=0LL;
	while(buf[idx]>='0'){
		var=var*10LL-(long long)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(double &var){
	if(!buf[idx]){
		var=0.0;
		return *this;
	}
	double sign=-1.0;
	if(buf[idx]=='-'){
		sign=1.0;
		if(++idx==siz) scan();
	}
	var=0.0;
	while(buf[idx]>='0'){
		var=var*10.0-(double)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	if(buf[idx]=='.'){
		if(++idx==siz) scan();
		double dig=1.0;
		while(buf[idx]>='0'){
			var-=(double)(buf[idx]-'0')*(dig/=10.0);
			if(++idx==siz) scan();
		}
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(long double &var){
	if(!buf[idx]){
		var=0.0L;
		return *this;
	}
	long double sign=-1.0L;
	if(buf[idx]=='-'){
		sign=1.0L;
		if(++idx==siz) scan();
	}
	var=0.0L;
	while(buf[idx]>='0'){
		var=var*10.0L-(long double)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	if(buf[idx]=='.'){
		if(++idx==siz) scan();
		long double dig=1.0L;
		while(buf[idx]>='0'){
			var-=(long double)(buf[idx]-'0')*(dig/=10.0L);
			if(++idx==siz) scan();
		}
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(char *var){
	if(!buf[idx]){
		var[0]='\x00';
		return *this;
	}
	int ptr=0;
	while(buf[idx]>='!'){
		var[ptr++]=buf[idx];
		if(++idx==siz) scan();
	}
	var[ptr]='\x00';
	if(++idx==siz) scan();
	return *this;
}
template<class T>
inline void kin::get(T *var,int num){
	for(int i=0;i<num;++i) (*this)>var[i];
	return;
}

inline void kout::open(FILE *fpa,int siza){
	fp=fpa;
	buf=new char[siza];
	siz=siza;
	idx=0;
	return;
}
inline void kout::close(void){
	fp=nullptr;
	delete[] buf;
	buf=nullptr;
	siz=0;
	idx=0;
	return;
}
inline void kout::print(void){
	std::fwrite((void *)buf,(std::size_t)1,(std::size_t)idx,fp);
	idx=0;
	return;
}
inline kout &kout::operator<(char val){
	buf[idx]=val;
	if(++idx==siz) print();
	return *this;
}
inline kout &kout::operator<(int val){
	if(val<0){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1;
	char dig[10];
	int ptr=0;
	do{
		int tmp=val/10;
		dig[ptr++]=(char)-(val-tmp*10)+'0';
		val=tmp;
	}while(val);
	while(ptr--){
		buf[idx]=dig[ptr];
		if(++idx==siz) print();
	}
	return *this;
}
inline kout &kout::operator<(long long val){
	if(val<0LL){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1LL;
	char dig[19];
	int ptr=0;
	do{
		long long tmp=val/10LL;
		dig[ptr++]=(char)-(val-tmp*10LL)+'0';
		val=tmp;
	}while(val);
	while(ptr--){
		buf[idx]=dig[ptr];
		if(++idx==siz) print();
	}
	return *this;
}
inline kout &kout::operator<(double val){
	if(val<0.0){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1.0;
	double dig=1.0;
	while(val/dig<=-10.0) dig*=10.0;
	int tmp;
	while(dig>=1.0){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(double)tmp*dig;
		dig/=10.0;
	}
	buf[idx]='.';
	if(++idx==siz) print();
	for(int i=0;i<12;++i){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(double)tmp*dig;
		dig/=10.0;
	}
	return *this;
}
inline kout &kout::operator<(long double val){
	if(val<0.0L){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1.0L;
	long double dig=1.0L;
	while(val/dig<=-10.0L) dig*=10.0L;
	int tmp;
	while(dig>=1.0L){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(long double)tmp*dig;
		dig/=10.0L;
	}
	buf[idx]='.';
	if(++idx==siz) print();
	for(int i=0;i<16;++i){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(long double)tmp*dig;
		dig/=10.0L;
	}
	return *this;
}
inline kout &kout::operator<(const char *val){
	for(int i=0;val[i];++i){
		buf[idx]=val[i];
		if(++idx==siz) print();
	}
	return *this;
}
template<class T>
inline void kout::put(T *val,int num,char spc,char end){
	--num;
	for(int i=0;i<num;++i) (*this)<val[i]<spc;
	(*this)<val[num]<end;
	return;
}


#define _CRT_SECURE_NO_WARNINGS

#include "bits/stdc++.h"
#ifdef _MSC_VER
int getchar_unlocked() { return getchar(); }
#endif
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define FOR(i, m, n) for(int i=(m); i<(n); ++i)
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mp make_pair
#define pb push_back
#define dump(x) cerr << #x << " = " << (x) << endl;
#define qp(f) [](auto i){return f;}
using LL=long long;
using VI=vector<int>;
using VL=vector<LL>;
using VS=vector<string>;
using VVI=vector<vector<int>>;
using PII=pair<int, int>;
const int inf = (int)1e9;
const LL MOD = 1000000007;
const double pi = acos(-1.0);
const string Snum = "0123456789";
const int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
template<class T>T Sort(T& a) { sort(a.begin(), a.end()); return a; }
template<class T>T ReSort(T& a) { sort(a.rbegin(), a.rend()); return a; }
template<class T>T Reverse(T& a) { reverse(a.begin(), a.end()); return a; }
template<class T>void Unique(T& a) { a.erase(unique(a.begin(), a.end()), a.end()); }
template<class T>auto Max(T a) { return *max_element(a.begin(), a.end()); }
template<class T>auto Min(T a) { return *min_element(a.begin(), a.end()); }
template<class T, class U>int Count(T a, U c) { return count(a.begin(), a.end(), c); }
template<class T, class U>U Sum(T a, U init = 0) { return accumulate(a.begin(), a.end(), init); }
template<class T>T Age(T a, T b) { return (a + b - 1) / b; }
template<class T>T gcd(T n, T m) { return m == 0 ? n : gcd(m, n % m); }
template<class T>T lcm(T n, T m) { return n / gcd(n, m) * m; }

/* RANGE */
namespace RangeNameSpace {
	template<class T>class Range {
		const T start_, stop_, step_;
	public:
		Range(const T& start, const T& stop, const T& step) : start_{ start }, stop_{ stop }, step_{ step } {assert(!(step_ == 0 || (start_ > stop_ && step_ > 0) || (start_ < stop_ && step_ < 0))); }
		class iterator {
			T value_; const T start_, stop_, step_;
		public:
			using value_type = T;
			iterator(T value, T step, T start, T stop) : value_{ value }, step_{ step }, start_{ start }, stop_{ stop } {}
			iterator operator++() { value_ = std::min(std::max(start_, stop_), std::max(std::min(start_, stop_), value_ + step_)); return *this; }
			iterator operator--() { value_ = std::min(std::max(start_, stop_), std::max(std::min(start_, stop_), value_ - step_)); return *this; }
			T& operator*() { return value_; }
			const T* operator->() { return &value_; }
			bool operator==(const iterator& rhs) { return value_ == rhs.value_; }bool operator!=(const iterator& rhs) { return value_ != rhs.value_; }
		};
		T operator[](size_t i) { return start_ + i * step_; }
		size_t size() { return (max(stop_, start_) - min(stop_, start_)) / abs(step_); }
		iterator begin() const { return iterator(start_, step_, start_, stop_); }
		iterator end() const { return iterator(stop_, step_, start_, stop_); }
		explicit operator vector<T>() const { vector<T>t; for (T i = start_; i < stop_; i += step_)t.push_back(i); return t; }
	};

	template <class T, class Func, class FuncType>class Range2 {
		using Itr = class T::iterator; Itr begin_, end_; Func f_;
	public:
		Range2(T v, Func f) : begin_{ v.begin() }, end_{ v.end() }, f_{ f } {}
		class iterator {
		public:
			typedef forward_iterator_tag iterator_category; iterator(Itr itr, Func f) : itr_{ itr }, f_{ f } {}
			iterator operator++() { ++itr_; return *this; }
			iterator operator--() { --itr_; return *this; }
			FuncType operator*() { return f_(*itr_); }
			bool operator==(iterator rhs) { return rhs.itr_ == itr_; }bool operator!=(iterator rhs) { return rhs.itr_ != itr_; }
		private:Itr itr_; Func f_;
		};
		size_t size() { return begin_.size(); }
		iterator begin() const { return iterator(begin_, f_); }
		iterator end() const { return iterator(end_, f_); }
		operator vector<FuncType>() const { vector<FuncType>t; for (Itr i = begin_; i != end_; ++i)t.push_back(f_(*i)); return t; }
	};

}
template<class T> RangeNameSpace::Range<T> range(const T& stop) { return RangeNameSpace::Range<T>(T{ 0 }, stop, T{ 1 }); }
template<class T> RangeNameSpace::Range<T> range(const T& start, const T& stop) { return RangeNameSpace::Range<T>(start, stop, T{ 1 }); }
template<class T> RangeNameSpace::Range<T> range(const T& start, const T& stop, const T& step) { return RangeNameSpace::Range<T>(start, stop, step); }
template<class _T> ostream& operator << (ostream& ostr, const vector<_T>& v) { if (v.size() == 0) { ostr << ""; return ostr; }ostr << v.front(); for (auto itr = ++v.begin(); itr != v.end(); itr++)ostr << " " << *itr; return ostr; }
template<class T> ostream& operator << (ostream& ostr, const RangeNameSpace::Range<T>& r) { ostr << vector<T>(r); return ostr; }
template<class T, class Func, class FuncType> ostream& operator << (ostream& ostr, const RangeNameSpace::Range2<T, Func, FuncType>& r) { ostr << vector<FuncType>(r); return ostr; }
template<class T, class Func> auto operator | (T v, Func f) { RangeNameSpace::Range2<T, Func, decltype(f(*v.begin()))>r(v, f); return r; }

/* INPUT */
struct inputter_Str {
	vector<string> inputbuffer;
	string operator [](int n) {
		while (inputbuffer.size() <= n) {
			string s; //cin >> s;
			char c = getchar_unlocked();
			while (c != '\0' && c != '\n' && c != '\t' && c != ' ') {
				s.push_back(c);
				c = getchar_unlocked();
			}inputbuffer.push_back(s);
		}
		return inputbuffer[n];
	}
	operator string() {
		string s;
		char c = getchar_unlocked();
		while (c != '\0' && c != '\n' && c != '\t' && c != ' ') {
			s.push_back(c);
			c = getchar_unlocked();
		}inputbuffer.push_back(s);
		return s;
	}
}in;
struct inputter_Int {
	int operator [](int n) {
		//string s; //cin >> s;
		return stoi(in[n]);
	}
	operator int() { return stoi(string(in)); }
}ini;

struct inputter_LL {
	long long operator [](int n) { return stoll(in[n]); }
	operator long long() { return stoll(string(in)); }
}inl;
struct inputter_Double {
	double operator [](int n) { return stod(in[n]); }
	operator double() { return stold(string(in)); }
}ind;
vector<int>       invi(int n, int m) { vector<int> v(m); for (int i = 0; i < m; ++i)v[i] = ini[n + i]; return v; }
vector<long long> invl(int n, int m) { vector<long long> v(m); for (int i = 0; i < m; ++i)v[i] = inl[n + i]; return v; }
vector<string>    invs(int n, int m) { vector<string> v(m); for (int i = 0; i < m; ++i)v[i] = in[n + i]; return v; }
int Suminvi(int n, int m) { return Sum(invi(n, m), 0); }long long Suminvl(int n, int m) { return Sum(invl(n, m), 0LL); }
int Maxinvi(int n, int m) { return Max(invi(n, m)); }   long long Maxinvl(int n, int m) { return Max(invl(n, m)); }
int Mininvi(int n, int m) { return Min(invi(n, m)); }   long long Mininvl(int n, int m) { return Min(invl(n, m)); }

struct inputter_Int_Fast {
	int get() {
		int num = 0;
		bool neg = false;
		char c = getchar_unlocked();
		if (c == '-') {
			neg = true;
			c = getchar_unlocked();
		}
		while ('0' <= c && c <= '57') {
			num = num * 10 + (c - '0');
			c = getchar_unlocked();
		}
		return neg ? -num : num;
	}
	operator int() { return get(); }
}inif;
struct inputter_LL_Fast {
	int get() {
		LL num = 0;
		bool neg = false;
		char c = getchar_unlocked();
		if (c == '-') {
			neg = true;
			c = getchar_unlocked();
		}
		while ('0' <= c && c <= '57') {
			num = num * 10LL + LL(c - '0');
			c = getchar_unlocked();
		}
		return neg ? -num : num;
	}
	operator LL() { return get(); }
}inlf;
vector<int>invif(int n) {
	vector<int> v(n);
	for (int i = 0; i < n; ++i) {

		int num = 0;
		bool neg = false;
		char c = getchar_unlocked();
		if (c == '-') {
			neg = true;
			c = getchar_unlocked();
		}
		while ('0' <= c && c <= '57') {
			num = num * 10 + (c - '0');
			c = getchar_unlocked();
		}
		v[i] = neg ? -num : num;
	}
	return v;
}
vector<LL>invlf(int n) {
	vector<LL> v(n);
	for (int i = 0; i < n; ++i) {
		LL num = 0;
		bool neg = false;
		char c = getchar_unlocked();
		if (c == '-') {
			neg = true;
			c = getchar_unlocked();
		}
		while ('0' <= c && c <= '57') {
			num = num * 10LL + LL(c - '0');
			c = getchar_unlocked();
		}
		v[i] = neg ? -num : num;
	}
	return v;
}

ostream& operator << (ostream& ostr, inputter_Str i) { ostr << string(i); return ostr; }

/* OUTPUT */
struct boolswitch { string t, f; boolswitch(string tr, string fa) :t(tr), f(fa) {} }yes("yes", "no"), Yes("Yes", "No"), YES("YES", "NO"), Yay("Yay!", ":(");
struct divizer { string s; divizer(string s_) :s(s_) {} }spc(" "), nosp(""), comma(",");
struct outputter {
	bool flag = false; boolswitch bs; divizer di;
	outputter(bool f, boolswitch b, divizer d) :flag(f), bs(b), di(d) {}
	template<class T>outputter operator ,(T o) {
		if (flag)cout << di.s; cout << o;
		outputter t(true, bs, di); return t;
	}
	outputter operator ,(double o) {
		if (flag)cout << di.s; printf("%.20f", o);
		outputter t(true, bs, di); return t;
	}
	outputter operator ,(bool o) {
		if (flag)cout << di.s; cout << (o ? bs.t : bs.f);
		outputter t(true, bs, di); return t;
	}
	template<class T> outputter operator ,(vector<T> o) {
		if (flag)cout << di.s;
		for (int i = 0; i < (int)o.size(); ++i)cout << o[i] << (i == (int)o.size() - 1 ? "" : di.s);
		outputter t(true, bs, di); return t;
	}
	template<class T, class U> outputter operator ,(pair<T, U> o) {
		if (flag)cout << di.s;
		cout << "[" << o.first, ", " << o.second << "]";
		outputter t(true, bs, di); return t;
	}
	outputter operator ,(outputter o) { cout << '\n'; return o; }
	outputter operator ,(boolswitch b) { outputter t(flag, b, di); return t; }
	outputter operator ,(divizer d) { outputter t(flag, bs, d); return t; }
}out(false, Yes, spc);

/* ANSWER */
struct Answer {
	int       mini = INT_MAX, maxi = INT_MIN, sumi = 0;
	long long minl = LLONG_MAX, maxl = LLONG_MIN, suml = 0LL;
	double    mind = DBL_MAX, maxd = DBL_MIN, sumd = 0.;
	int count = 0;
	void operator =(int n) { mini = min(mini, n); maxi = max(maxi, n); sumi += n; count++; }
	void operator =(long long n) { minl = min(minl, n); maxl = max(maxl, n); suml += n; count++; }
	void operator =(double n) { mind = min(mind, n); maxd = max(maxd, n); sumd += n; count++; }
}ans;

/* SLICE */
struct IntNone {
	int val = 0; bool none = true;
	IntNone() :val(0), none(true) {};
	IntNone(int v) :val(v), none(false) {};
	operator int() { return val; }
}None;
struct Slicer {
	IntNone from_, to_, step_;
	Slicer(IntNone from, IntNone to, IntNone step) :from_(from), to_(to), step_(step) {}
};
Slicer sp(int from, int to, int step = 1) { return Slicer(from, to, step); }
Slicer sp(int from, IntNone to, int step = 1) { return Slicer(from, to, step); }
Slicer sp(IntNone from, int to, int step = 1) { return Slicer(from, to, step); }
Slicer sp(IntNone from, IntNone to, int step = 1) { return Slicer(from, to, step); }
template<class T>decltype(auto) operator |(T v, Slicer s) {
	typedef typename T::iterator::value_type Ty;
	vector<Ty> ret; int size = (int)v.size();
	if (s.step_ > 0) {
		if (s.from_.none)s.from_ = 0;
		if (s.from_ < 0)s.from_ = size + s.from_;
		if (s.to_ < 0)s.to_ = size + s.to_;
	}
	else if (s.step_ < 0) {
		if (s.from_.none)s.from_ = size;
		if (s.from_ < 0)s.from_ = size + s.from_;
		if (s.to_ < 0)s.to_ = size + s.to_;
	}
	if (s.step_ > 0)
		for (int i = max(s.from_.val, 0); (s.to_.none ? true : (i < s.to_)) && i < size && i >= 0; i += s.step_)ret.push_back(v[i]);
	else for (int i = min(s.from_.val, size - 1); (s.to_.none ? true : (i > s.to_)) && i >= 0; i += s.step_)ret.push_back(v[i]);
	return ret;
}

/* MOD */
long long modpow(long long a, long long n, long long _MOD = MOD) {
	long long re = 1;
	while (n > 0) {
		if (n & 1)re = re * a % _MOD;
		a = a * a % _MOD; n >>= 1;
	}
	return re;
}
long long modinv(long long n, long long _MOD = MOD) {
	return modpow(n, _MOD - 2, _MOD);
}
struct Modl {
	long long val = 0;
	Modl(long long v = 0)noexcept :val(v% MOD) { if (val < 0)v += MOD; }
	operator long long() { return val; }
};
Modl operator-(const Modl& a) { Modl r; r.val = a.val ? MOD - a.val : 0; return r; }
Modl operator+(const Modl& a, const Modl& b) { Modl r(a.val + b.val); return r; }
Modl operator-(const Modl& a, const Modl& b) { Modl r(a.val - b.val); return r; }
Modl operator*(const Modl& a, const Modl& b) { Modl r(a.val * b.val); return r; }
Modl operator/(const Modl& a, const Modl& b) { Modl r(a.val * modinv(b.val, MOD)); return r; }
Modl operator+(const Modl& a, const int& b) { Modl r(a.val + LL(b)); return r; }
Modl operator-(const Modl& a, const int& b) { Modl r(a.val - LL(b)); return r; }
Modl operator*(const Modl& a, const int& b) { Modl r(a.val * LL(b)); return r; }
Modl operator/(const Modl& a, const int& b) { Modl r(a.val * modinv(LL(b), MOD)); return r; }
Modl operator+(const Modl& a, const long long& b) { Modl r(a.val + b); return r; }
Modl operator-(const Modl& a, const long long& b) { Modl r(a.val - b); return r; }
Modl operator*(const Modl& a, const long long& b) { Modl r(a.val * b); return r; }
Modl operator/(const Modl& a, const long long& b) { Modl r(a.val * modinv(b, MOD)); return r; }
Modl operator-(const int& a, const Modl& b) { Modl r(LL(a) - b.val); return r; }
Modl operator*(const int& a, const Modl& b) { Modl r(LL(a) * b.val); return r; }
Modl operator/(const int& a, const Modl& b) { Modl r(LL(a) * modinv(b.val, MOD)); return r; }
Modl operator+(const int& a, const Modl& b) { Modl r(LL(a) + b.val); return r; }
Modl operator+(const long long& a, const Modl& b) { Modl r(a + b.val); return r; }
Modl operator-(const long long& a, const Modl& b) { Modl r(a - b.val); return r; }
Modl operator*(const long long& a, const Modl& b) { Modl r(a * b.val); return r; }
Modl operator/(const long long& a, const Modl& b) { Modl r(a * modinv(b.val, MOD)); return r; }
Modl pow(Modl a, int n) { Modl r(modpow(a, n)); return r; }
Modl pow(Modl a, long long n) { Modl r(modpow(a, n)); return r; }

/* age */
struct agel { long long val; agel(long long i) : val(i) {} };
agel operator"" age(unsigned long long i) { return agel(i); }
long long operator/(const long long& a, const agel& b) { return Age(a, b.val); }
struct ATFIRST {
	ATFIRST() {}
}ATFIRST_;

int main() {
	int n = inif;
	VL a = invlf(n);
	LL b = 1;
	for (int i = 1; i <= n; i++) {
		if (2 == (b = a[b - 1])) {
			out, i, out;
			return 0;
		}
	}
	out, -1, out;
}


#include <bits/stdc++.h>
#define FOR(i, a, n) for (int i = a; i < n; i++)
#define REP(w, n) FOR(w, 0, n)
using namespace std;
typedef long long ll;

int main()
{
	int n;
	cin >> n;
	int a[n];

	REP(i, n)
	{
		cin >> a[i];
	}
	int on = 0;
	int count = 0;
	while (a[on] != 1)
	{
		on = a[on] - 1;
		count++;
		if (on == 1)
		{
			cout << count << '\n';
			return (0);
		}
	}
	cout << -1 << '\n';
	return (0);
}


#include<iostream>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<string.h>
using namespace std;

int main(){
	std::ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	int n, m,on=0,off=0; cin >> n; bool flag =true;
	for (int i = 0; i < n; i++) {
		cin >> m;
		if (flag==true) {
			on++;
			flag = false;
		}
		else {
			off++;
			flag = true;
		}

	}
	if (on > off)cout << on << endl;
	else cout << -1 << endl;

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define M 1000000007
long long int power(int a,int b)
{
    if(b==0)
        return 1;
    long long int k=power(a,b/2);
    if(b%2==0)
        return ((k%M)*(k%M))%M;
    else
        return ((k%M)*(k%M)*(a%M))%M;
}
long long int fact(long long int n)
{
    if(n==1 || n==0)
        return 1;
    else
        return ((n%M)*(fact(n-1)%M))%M;

}
int div(int n)
{  int c=0;
    for(int i=1;i<=sqrt(n);i++)
    {
        if(n%i==0)
        {
          if(n/i==i)
            c++;
          else
            c+=2;
        }

    }

    return  c;
}
int func(int n)
{
    return (n*(n+1))/2;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
     #ifndef ONLINE_JUDGE

    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);

   #endif

   int n;
   cin>>n;
   int arr[n];
   bool g=false;
   for(int i=0;i<n;i++)
   {
      cin>>arr[i];
      if(arr[i]==2)
        g=true;
   }
     if(g==false)
     {
        cout<<-1;
        return 0;
     }
  int a=1;
  int c=0;
  int k;
  while(1)
  {
    k=a;
    a=arr[a-1];

    c++;
    if(a==2)
    {
       cout<<c;
       return 0;
    }
     if(arr[a-1]==k && arr[a-1])
    {
       cout<<-1;
       return 0;
    }

  }

 return 0;
}


#include <unistd.h>
#include <stdlib.h>

void writing(int ans)
{
    char c;
    if (ans < 10)
    {
        c = ans + '0';
        write(1, &c, 1);
    }
    else
    {
        writing(ans / 10);
        writing(ans % 10);
    }
}

int get_num(char *s)
{
    int num;
    int i;

    i = -1;
    while (s[++i] != 10)
    {
        if (s[i] != 32)
        {
            num = 0;
            while ('0' <= s[i] && s[i] <= '9')
            {
                num = num * 10 + s[i++] - '0';

            }
            return (num);
        }
    }
}

void get_nums(int *array, char *s, int count)
{
    int num;
    int i;

    i = -1;
    while (s[++i])
    {
        if (s[i] != 10 && s[i] != 32)
        {
            num = 0;
            while ('0' <= s[i] && s[i] <= '9')
            {
                num = num * 10 + s[i++] - '0';
                if (!s[i])
                {
                    array[count] = num;
                    return ;
                }
            }
            array[count++] = num;
            i--;
        }
    }
}

void get_num_plus(int *tab, char *tmp, int pass_flag, int count)
{
    int i;

    i = -1;
    while (count < pass_flag)
    {
        while (tmp[++i] != 10)
            ;
        count++;
    }
    get_nums(tab, &tmp[++i], 0);
}

void get_ans(int n, char *tmp)
{
    int i;
    int j;
    int tab[n];
    int count;

    get_num_plus(tab, tmp, 1, 0);
    count = 0;
    j = 0;
    i = -1;
    while (++i < n)
    {
        count++;
        if (tab[j] == 2)
        {
            writing(count);
            return ;
        }
        j = tab[j] - 1;
    }
    write(1, "-1", 2);
}

char *create_array(char *s, char *new_arr, char *t, int size)
{
    int i;
    int j;

    i = -1;
    while (s[++i])
        new_arr[i] = s[i];
    free(s);
    j = 0;
    while (j < size)
        new_arr[i++] = t[j++];
    new_arr[i] = 0;
    return (new_arr);
}

char *get_data(char *s)
{
    int size;
    int sum_size;
    char t[10000000];
    char *new_arr;

    sum_size = 0;
    while ((size = read(0, t, 10000000)))
    {
        if (size == -1)
            return (NULL);
        sum_size += size;
        if (!(new_arr = (char*)malloc(sum_size + 1)))
            return (NULL);
        s = create_array(s, new_arr, t, size);
    }
    return (s);
}

int main(void){
    int num;
    char *s;

    s = malloc(1);
    s = get_data(s);
    num = get_num(s);
    get_ans(num, s);
    free(s);
    return (0);
}


i,a[1<<17],b[1<<17];c;
buf[1145141];char*p=buf;
main(s){
	for(read(0,buf,1000000);*p;p++)if(*p>10)a[i]=a[i]*10+*p-48;else ++i;
	for(b[i=s]=1;!b[s=a[s]]++&&s-2;i++);
	printf("%d",s==2?i:-1);
}


i,a[1<<17],b[1<<17];c;
main(s){
	for(;~(c=getchar_unlocked());)if(c>10)a[i]=a[i]*10+c-48;else ++i;
	for(b[i=s]=1;!b[s=a[s]]++&&s-2;i++);
	printf("%d",s-2?-1:i);
}


#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{
    long N;
    int i,p;
    long a[100001] = {0};
    long count = 0;
    long pp[100001] = {1};

    scanf("%ld", &N);

    for (i = 1; i <= N; i++) {
        scanf("%ld", &a[i]);
    }

    i = 1;
    pp[i++] = p = a[1];
    count++;

    while (1) {

       pp[i++] = p = a[p];
       count++;

       if (p == 2)
           break;

       for (int j = 0; j < i - 1; j++) {
           if (p == pp[j]) {
               printf("-1");
               return 0;
           }
       }

    }

    printf("%ld", count);

    return 0;

}


#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{
    long N;
    int i,p;
    long a[100001] = {0};
    long count = 0;
    long pp[100000] = {1};

    scanf("%ld", &N);

    for (i = 1; i <= N; i++) {
        scanf("%ld", &a[i]);
    }

    i = 1;
    pp[i++] = p = a[1];
    count++;

    while (1) {

       pp[i++] = p = a[p];
       count++;

       if (p == 2)
           break;

       for (int j = 0; j < i - 1; j++) {
           if (p == pp[j]) {
               printf("-1");
               return 0;
           }
       }

    }

    printf("%ld", count);

    return 0;

}


#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{
    long N;
    int i,p;
    long a[100001] = {0};
    long count = 0;
    long pp[10000] = {1};

    scanf("%ld", &N);

    for (i = 1; i <= N; i++) {
        scanf("%ld", &a[i]);
    }

    i = 1;
    pp[i++] = p = a[1];
    count++;

    while (1) {

       pp[i++] = p = a[p];
       count++;

       if (p == 2)
           break;

       for (int j = 0; j < i - 1; j++) {
           if (p == pp[j]) {
               printf("-1");
               return 0;
           }
       }

    }

    printf("%ld", count);

    return 0;

}


'use strict'

function main(s) {

  s = s.split('\n');
  const N = Number(s[0]);
  const buttons = s.slice(1, -1).map(n => Number(n));

  let ans = -1;

  for (var i = 1, j = 0; i <= N; i++) {
    j = buttons[j] - 1;

    if (j === 1) {
      ans = i;
      break;
    }
  }

  console.log(ans);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = ~~arg[0];
    const S = arg.slice(1, N + 1).map(n=>~~n);

    let now = 1;
    let cnt = 0;

    while(now !== 2) {
        now = S[now - 1];
        cnt++;

        if(cnt > N) {
            console.log(-1);
            return;
        }
    }

    console.log(cnt);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  input = input.split('\n');

  var n = parseInt(input[0], 10);
  var a = [];
  for (var i = 0; i < n; i++) {
    a[i + 1] = parseInt(input[i + 1], 10);
  }

  var cur = 1;
  for (var i = 0; i < n + 100; i++) {
    if (a[cur] == 2) {
      console.log(i + 1);
      return;
    }
    cur = a[cur];
  }

  console.log(-1);
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


console.log((args=>{
  let [N,...a] = args.trim().split`\n`.map(v=>v-1);
  let c = a[0];
  for ( let i = 1; i <= N; i++ ) {
    c = a[c];
    if ( c === 1 ) return i+1;
  }
  return '-1';
})(require('fs').readFileSync('/dev/stdin', 'utf8')));


'use strict';
function Main(stdin){
  const input = stdin.trim().split(/\r?\n/g).map(str => Number(str));
  const N = input.shift();
  let btn_num = 2;
  let result = -1;
  let count = 0;

  for(let i = 0; i < N; i++){
      if(input.indexOf(btn_num) > -1){
        btn_num = input.indexOf(btn_num) + 1;
        count++;
        if(btn_num === 1){
            result = count;
            break;
        }
      } else {
          break;
      }
  }
  console.log(result);
}

// 固定
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = arg.slice(1, N + 1).map(n=>parseInt(n));

    let now = 0;
    let cnt = 0;
    let done = [];

    while(true) {
        now = A[now] - 1;

        if(now === 1) {
            cnt++;
            console.log(cnt);
            return;
        }

        cnt++;

        console.log("now:" + now)
        console.log("done:" + done)

        if(done.indexOf(now) !== -1) {
            console.log(-1);
            return;
        }

        done.push(now);
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


package main

import (
	"bufio"
	"fmt"
	"os"
)

var sc = bufio.NewScanner(os.Stdin)

func r() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func main() {
	sc.Split(bufio.ScanWords)
	n := r()

	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = r() - 1
	}

	var nowIdx int
	var ct int
	for {
		nextIdx := a[nowIdx]

		if ct >= n {
			ct = -1
			break
		}

		if nowIdx == 1 {
			break
		}

		nowIdx = nextIdx
		ct++
	}
	fmt.Println(ct)
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var sc = bufio.NewScanner(os.Stdin)

func r() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func main() {
	sc.Split(bufio.ScanWords)
	n := r()

	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = r() - 1
	}

	var nowIdx int
	var ct int
	for {
		nextIdx := a[nowIdx]

		a[nowIdx] = -1

		if nextIdx == -1 {
			ct = -1
			break
		}

		if nowIdx == 1 {
			break
		}

		nowIdx = nextIdx
		ct++
	}
	fmt.Println(ct)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func NextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}

func main() {
	n := NextInt()
	a := make([]int, n)
	for i := range a {
		a[i] = NextInt() - 1
	}

	var now, cnt int
	for {
		if now == 1 {
			fmt.Println(cnt)
			break
		}

		if cnt >= n {
			fmt.Println(-1)
			break
		}

		cnt++
		now = a[now]
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func BufScan(n int) []string {
	var in []string
	sc := bufio.NewScanner(os.Stdin)
	for i := 0; i < n; i++ {
		sc.Scan()
		in = append(in, sc.Text())
	}

	return in
}

func IntBufScan(n int) []int {
	var inInts []int
	inStrings := BufScan(n)
	for _, i := range inStrings {
		tmp, _ := strconv.Atoi(i)
		inInts = append(inInts, tmp)
	}
	return inInts
}

func main() {
	n := 0
	fmt.Scanf("%d", &n)
	a := IntBufScan(n)
	m := 1
	for i := 1; ; i++ {
		m = a[m-1]
		if m == 1 {
			fmt.Println("-1")
			return
		}
		if m == 2 {
			fmt.Println(i)
			return
		}
	}
}


package main

import "fmt"

func main() {
	n := 0
	var a []int
	a = append(a, 0)

	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		tmp := 0
		fmt.Scanf("%d", &tmp)
		a = append(a, tmp)
	}

	m := 1
	for i := 1; ; i++ {
		m = a[m]
		if m == 1 {
			fmt.Println("-1")
			return
		}
		if m == 2 {
			fmt.Println(i)
			return
		}
	}
}


n = gets.to_i
as = $<.map(&:to_i)
i = 0
ans = 0
n.times {
  i = as[i] - 1
  ans += 1
  break if i == 1
}
puts (i == 1 ? ans : -1)


button = $stdin.read.split("\n")
button.map! do |element|
	element.to_i
end
button.shift()
#p button
#p button.size
current = 1
cnt = 0
while true
	if current == 2
		print("#{cnt}\n")
		break
	elsif cnt >= button.size
		print("-1\n")
		break
	end
	cnt += 1
	current = button[current-1]
end


n = gets.to_i
num = []
n.times do
  num << gets.to_i
end

rec = [1] #光ったことのあるボタンを記録
i = 0
while i >= 0 do
  unless rec.include?(num[rec[i]-1])
    rec << num[rec[i]-1]
  else
    break
  end
  i += 1
end
if rec.include?(2)
  puts rec.index(2)
else
  puts "-1"
end


N = gets.to_i
a = N.times.map{ (gets.chomp.to_i) -1 }
cnt = 1
i = a[0]
a[0] = -1

while true
  if a[i] == 1
    cnt += 1
    break
  elsif a[i] == -1
    cnt = -1
    break
  else
    tmp = i
    i = a[i]
    a[tmp] = -1
    cnt += 1
  end
end

puts cnt


#include <bits/stdc++.h>
using namespace std;

int main() {
  int n;
  cin >> n;

  vector<int> buttons(n);

  for (int i = 0; i < n; i++) {
    int a;
    cin >> a;
    buttons.at(i) = a;
  }

  bool ok = false;
  int cnt = 0;
  int pos = 0;
  while (true) {
    int nextPos = buttons.at(pos);
    cnt++;
    if (nextPos == 2) {
      ok = true;
      break;
    }
    if (nextPos - 1 == pos) {
      break;
    }

    pos = nextPos - 1;
  }

  if (ok) {
    cout << cnt << endl;
  } else {
    cout << -1 << endl;
  }
}


/*------------------------------------------------------------------*/
/*------------------------- begin template -------------------------*/
/*------------------------------------------------------------------*/

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, char_) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()[0]
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

use std::io;
use std::io::BufRead;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    pub reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
    pub fn fast_i64(&mut self) -> i64 {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            if begin == self.buf.len() {
                self.update_buf();
                continue;
            }
            let mut res = 0;
            let (is_positive, mut end) = match self.buf[begin] {
                b'+' => (true, begin + 1),
                b'-' => (false, begin + 1),
                _ => (true, begin),
            };
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return if is_positive { res } else { -res };
            } else {
                self.update_buf();
            }
        }
    }
}

#[allow(unused_imports)]
use std::cmp::*;

fn main() {
    input! {
        new_stdin_parser = parser,
    }
    let res = solve(&mut parser);
    print!("{}", res);
}

/*------------------------------------------------------------------*/
/*-------------------------- end template --------------------------*/
/*------------------------------------------------------------------*/

use std::fmt::Write;
fn solve<R: BufRead>(parser: &mut Parser<R>) -> String {
    let mut buf = String::new();
    input! {
        parser = parser,
        n: usize,
        xs: [usize1; n],
    }
    let mut visited = vec![false; n];
    let mut i = 0;
    let mut res = 0;
    loop {
        if visited[i] {
            writeln!(buf, "-1");
            return buf;
        }
        if i == 1 {
            break;
        }
        visited[i] = true;
        i = xs[i];
        res += 1;
    }
    writeln!(buf, "{}", res);
    buf
}


fn main() {
	let mut s = String::new();
	use std::io::Read;
	std::io::stdin().read_to_string(&mut s).unwrap();
	let mut s = s.split_whitespace();
	let n: usize = s.next().unwrap().parse().unwrap();
	let a: Vec<_> = s.map(|a| a.parse::<i32>().unwrap() - 1).collect();
	let mut visit = vec![false; n];
	let mut cur = 0;
	let mut ans = 0;
	while !visit[cur] {
		visit[cur] = true;
		cur = a[cur] as usize;
		ans += 1;
		if cur == 1 {
			println!("{}", ans);
			return;
		}
	}
	println!("-1");
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: usize,
        lit_by: [usize1; n],
    }
    let mut seen = vec![-1; n];
    let mut now_on = 0usize;
    for i in 0.. {
        let dist = seen.get_mut(now_on).unwrap();
        if *dist != -1 { break; }
        *dist = i;
        if now_on == 1 { break; }

        now_on = *lit_by.get(now_on).unwrap();
    }
    println!("{}", seen[1]);
}