use std::collections::VecDeque; fn main() { let (n, m) = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse::().unwrap(), iter.next().unwrap().parse::().unwrap(), ) }; let uv: Vec<_> = (0..m) .map(|_| { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse::().unwrap() - 1, iter.next().unwrap().parse::().unwrap() - 1, ) }) .collect(); let mut graph = vec![vec![]; n]; for &(u, v) in &uv { graph[u].push(v); } let u = n - 2; let v = n - 1; let dists_0 = calc_distances(&graph, 0); let dists_u = calc_distances(&graph, u); let dists_v = calc_distances(&graph, v); let mut ans = None; if let (Some(d1), Some(d2), Some(d3)) = (dists_0[u], dists_u[v], dists_v[0]) { update_cost(&mut ans, d1 + d2 + d3); } if let (Some(d1), Some(d2), Some(d3)) = (dists_0[v], dists_v[u], dists_u[0]) { update_cost(&mut ans, d1 + d2 + d3); } if let (Some(d1), Some(d2), Some(d3), Some(d4)) = (dists_0[u], dists_u[v], dists_v[u], dists_u[0]) { update_cost(&mut ans, d1 + d2 + d3 + d4); } if let (Some(d1), Some(d2), Some(d3), Some(d4)) = (dists_0[v], dists_v[u], dists_u[v], dists_v[0]) { update_cost(&mut ans, d1 + d2 + d3 + d4); } match ans { Some(ans) => println!("{}", ans), None => println!("-1"), } } fn update_cost(cost: &mut Option, cand_cost: usize) { if cost.is_none() || cand_cost < cost.unwrap() { *cost = Some(cand_cost); } } fn calc_distances(graph: &[Vec], start: usize) -> Vec> { let n = graph.len(); let mut dists = vec![None; n]; let mut queue = VecDeque::from([(start, 0)]); while let Some((cur, dist)) = queue.pop_front() { if dists[cur].is_some() { continue; } dists[cur] = Some(dist); for &next in &graph[cur] { queue.push_back((next, dist + 1)); } } dists }