/* -*- coding: utf-8 -*- * * 2565.cc: No.2565 はじめてのおつかい - yukicoder */ #include #include #include #include using namespace std; /* constant */ const int MAX_N = 100000; const int INF = 1 << 30; /* typedef */ typedef vector vi; typedef queue qi; /* global variables */ vi nbrs[MAX_N]; int ds[MAX_N]; /* subroutines */ void bfs(int n, int st) { fill(ds, ds + n, INF); ds[st] = 0; qi q; q.push(st); while (! q.empty()) { int u = q.front(); q.pop(); int vd = ds[u] + 1; for (auto v: nbrs[u]) if (ds[v] > vd) { ds[v] = vd; q.push(v); } } } /* main */ int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; nbrs[u].push_back(v); } bfs(n, 0); int d01 = ds[n - 2], d02 = ds[n - 1]; bfs(n, n - 2); int d12 = ds[n - 1], d10 = ds[0]; bfs(n, n - 1); int d21 = ds[n - 2], d20 = ds[0]; int mind = INF; if (d01 < INF && d12 < INF && d20 < INF) mind = min(mind, d01 + d12 + d20); if (d02 < INF && d21 < INF && d10 < INF) mind = min(mind, d02 + d21 + d10); printf("%d\n", mind < INF ? mind : -1); return 0; }