use std::collections::{HashMap, HashSet}; use std::collections::VecDeque;
impl Solution { pubfnminimum_semesters(n: i32, relations: Vec<Vec<i32>>) -> i32 { letmut in_degrees = vec![0; n asusize + 1]; letmut map: HashMap<i32, HashSet<i32>> = HashMap::new(); for r in &relations { map.entry(r[0]).or_insert(HashSet::new()); map.get_mut(&r[0]).unwrap().insert(r[1]); in_degrees[r[1] asusize] += 1; }
letmut q = VecDeque::new(); let (mut ans, mut sum) = (0, 0); for i in1..n + 1 { if in_degrees[i asusize] == 0 { q.push_back(i); } }
while !q.is_empty() { let size = q.len(); sum += size; for _i in0..size { let cur = q.front().unwrap().clone(); q.pop_front(); if !map.contains_key(&cur) { continue; } for next in map.get(&cur).unwrap() { in_degrees[*next asusize] -= 1; if in_degrees[*next asusize] == 0 { q.push_back(*next); } } } ans += 1; } if sum == n asusize { return ans; } else { return -1; } } }