From ec5daaf058bf82e6ca79e6edfc0820de5dfb7bca Mon Sep 17 00:00:00 2001 From: Rodolfo P A <6721075+rodoufu@users.noreply.github.com> Date: Mon, 29 May 2023 14:25:54 -0300 Subject: [PATCH] Create find-if-path-exists-in-graph.rs --- .../graph/find-if-path-exists-in-graph.rs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 leetCode/graph/find-if-path-exists-in-graph.rs diff --git a/leetCode/graph/find-if-path-exists-in-graph.rs b/leetCode/graph/find-if-path-exists-in-graph.rs new file mode 100644 index 0000000..efe8718 --- /dev/null +++ b/leetCode/graph/find-if-path-exists-in-graph.rs @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/find-if-path-exists-in-graph/ +use std::collections::{ + HashMap, + HashSet, +}; + +impl Solution { + pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { + let mut graph: HashMap> = HashMap::new(); + for edge in edges { + graph.entry(edge[0]).or_default().insert(edge[1]); + graph.entry(edge[1]).or_default().insert(edge[0]); + } + + let mut visited = HashSet::from([source]); + let mut to_visit = vec![source]; + + while !to_visit.is_empty() { + let node = to_visit.pop().unwrap(); + if node == destination { + return true; + } + + if let Some(neighbors) = graph.get(&node) { + for neighbor in neighbors { + if !visited.contains(neighbor) { + visited.insert(*neighbor); + to_visit.push(*neighbor); + } + } + } + } + + false + } +}