LeetCode 1059. All Paths from Source Lead to Destination

Problem Statement


use std::collections::{HashMap, HashSet};

impl Solution {
fn dfs(g: &HashMap<i32, HashSet<i32>>, i: i32, des: i32, visited: &mut HashMap<i32, i32>) -> bool {
if !g.contains_key(&i) || g.get(&i).unwrap().is_empty() {
return i == des;
}
if visited.contains_key(&i) {
let val = visited.get(&i).unwrap();
if *val == 1 {
return false;
}
if *val == -1 {
return true;
}
} else {
visited.insert(i, 1);
}
for neib in g.get(&i).unwrap() {
if !Self::dfs(g, *neib, des, visited) {
return false;
}
}
visited.insert(i, -1);
return true;
}

pub fn leads_to_destination(n: i32, edges: Vec<Vec<i32>>, source: i32, destination: i32) -> bool {
let (mut g, mut visited) = (HashMap::new(), HashMap::new());
for e in edges {
if !g.contains_key(&e[0]) {
g.insert(e[0], HashSet::new());
}
let mut val = g.get(&e[0]).unwrap().clone();
val.insert(e[1]);
g.insert(e[0], val);
}
return Self::dfs(&g, source, destination, &mut visited);
}
}