Ensured correctness by using a dequeue for subsequent path walking

This commit is contained in:
boolpurist 2024-08-06 11:11:43 +02:00
parent 5dd43ae14d
commit 4b3ff681fe

View file

@ -1,6 +1,8 @@
pub struct Solution; pub struct Solution;
// Copy from here for submitting this solution to leet code // Copy from here for submitting this solution to leet code
use std::collections::VecDeque;
impl Solution { impl Solution {
pub fn can_jump(nums: Vec<i32>) -> bool { pub fn can_jump(nums: Vec<i32>) -> bool {
Solution::idiom_can_jump(&nums) Solution::idiom_can_jump(&nums)
@ -30,13 +32,14 @@ impl Solution {
return false; return false;
} }
let target_val = (nums.len() - 1) as i32; let target_val = (nums.len() - 1) as i32;
let mut next_nodes = Vec::from([(0, nums[0])]); // Using a dequeue ensures that every index is visited
let mut next_nodes = VecDeque::from([(0, nums[0])]);
// index visited yet // index visited yet
let mut visted_indices = -1; let mut greatest_visted_indices = -1;
if Self::check_with_target_value(target_val, 0) { if Self::check_with_target_value(target_val, 0) {
return true; return true;
} }
while let Some(next_node) = next_nodes.pop() { while let Some(next_node) = next_nodes.pop_front() {
let (index, steps) = next_node; let (index, steps) = next_node;
let max_jump_height = index + steps; let max_jump_height = index + steps;
if Self::check_with_target_value(target_val, max_jump_height) { if Self::check_with_target_value(target_val, max_jump_height) {
@ -45,12 +48,15 @@ impl Solution {
// It can start at 1 because the every index was checked in previous path walking // It can start at 1 because the every index was checked in previous path walking
for next_to_check in 1..=steps { for next_to_check in 1..=steps {
let to_add = index + next_to_check; let to_add = index + next_to_check;
if visted_indices >= to_add { // Going left to right and using a dequeue
// for subsequent path walking ensures that
// every index before to_add was visited.
if greatest_visted_indices >= to_add {
// already visited this index // already visited this index
continue; continue;
} }
visted_indices = to_add; greatest_visted_indices = to_add;
next_nodes.push((to_add, nums[to_add as usize])); next_nodes.push_front((to_add, nums[to_add as usize]));
} }
} }
false false