forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0207-course-schedule.rs
40 lines (31 loc) · 914 Bytes
/
0207-course-schedule.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
36
37
38
39
40
impl Solution {
pub fn can_finish(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool {
let mut graph = vec![vec![]; num_courses as usize];
let mut visited = vec![0; num_courses as usize];
for edge in prerequisites {
graph[edge[0] as usize].push(edge[1] as usize);
}
for i in 0..num_courses as usize {
if !Self::dfs(i, &graph, &mut visited) {
return false;
}
}
true
}
fn dfs(i: usize, graph: &Vec<Vec<usize>>, visited: &mut Vec<i32>) -> bool {
if visited[i] == 1 {
return false;
}
if visited[i] == -1 {
return true;
}
visited[i] = 1;
for j in graph[i].iter() {
if !Self::dfs(*j, graph, visited) {
return false;
}
}
visited[i] = -1;
true
}
}