Skip to content

Commit

Permalink
Create 0207-course-schedule.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
chojs23 committed Dec 6, 2023
1 parent d1f1400 commit 065b10d
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions rust/0207-course-schedule.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
}
}

0 comments on commit 065b10d

Please sign in to comment.