forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
35 lines (30 loc) · 956 Bytes
/
Solution.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::collections::VecDeque;
impl Solution {
pub fn can_finish(mut num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool {
let mut g: Vec<Vec<i32>> = vec![vec![]; num_courses as usize];
let mut indeg: Vec<i32> = vec![0; num_courses as usize];
for p in prerequisites {
let a = p[0] as usize;
let b = p[1] as usize;
g[b].push(a as i32);
indeg[a] += 1;
}
let mut q: VecDeque<usize> = VecDeque::new();
for i in 0..num_courses {
if indeg[i as usize] == 0 {
q.push_back(i as usize);
}
}
while let Some(i) = q.pop_front() {
num_courses -= 1;
for &j in &g[i] {
let j = j as usize;
indeg[j] -= 1;
if indeg[j] == 0 {
q.push_back(j);
}
}
}
num_courses == 0
}
}