AtCoder Beginner Contest 376 D

https://atcoder.jp/contests/abc376/tasks/abc376_d

幅優先探索します。

// Cycle
#![allow(non_snake_case)]

use std::collections::VecDeque;


//////////////////// library ////////////////////

fn read<T: std::str::FromStr>() -> T {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    line.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect()
}


//////////////////// Graph ////////////////////

type Node = usize;
type Edge = (Node, Node);

fn read_edge() -> Edge {
    let v: Vec<usize> = read_vec();
    let (a, b) = (v[0] - 1, v[1] - 1);
    (a, b)
}

struct Graph {
    g: Vec<Vec<Node>>
}

impl Graph {
    fn neighbors(&self, v: Node) -> &Vec<Node> {
        &self.g[v]
    }
    
    fn create_by_edges(N: usize, edges: Vec<Edge>) -> Graph {
        let mut g: Vec<Vec<Node>> = vec![vec![]; N];
        for (A, B) in edges.into_iter() {
            g[A].push(B);
        }
        Graph { g }
    }
}


//////////////////// process ////////////////////

fn read_input() -> (usize, Vec<Edge>) {
    let v: Vec<usize> = read_vec();
    let (N, M) = (v[0], v[1]);
    let edges: Vec<Edge> = (0..M).map(|_| read_edge()).collect();
    (N, edges)
}

fn F(N: usize, edges: Vec<Edge>) -> i32 {
    let graph = Graph::create_by_edges(N, edges);
    let mut queue: VecDeque<(Node, i32)> = VecDeque::new();
    queue.push_back((0, 0));
    while let Some((v0, d)) = queue.pop_front() {
        for &v in graph.neighbors(v0).iter() {
            if v == 0 {
                return d + 1
            }
            queue.push_back((v, d + 1))
        }
    }
    -1
}

fn main() {
    let (N, edges) = read_input();
    println!("{}", F(N, edges))
}