Ensured correctness by using a dequeue for subsequent path walking
This commit is contained in:
parent
5dd43ae14d
commit
4b3ff681fe
1 changed files with 12 additions and 6 deletions
18
src/lib.rs
18
src/lib.rs
|
@ -1,6 +1,8 @@
|
|||
pub struct Solution;
|
||||
|
||||
// Copy from here for submitting this solution to leet code
|
||||
|
||||
use std::collections::VecDeque;
|
||||
impl Solution {
|
||||
pub fn can_jump(nums: Vec<i32>) -> bool {
|
||||
Solution::idiom_can_jump(&nums)
|
||||
|
@ -30,13 +32,14 @@ impl Solution {
|
|||
return false;
|
||||
}
|
||||
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
|
||||
let mut visted_indices = -1;
|
||||
let mut greatest_visted_indices = -1;
|
||||
if Self::check_with_target_value(target_val, 0) {
|
||||
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 max_jump_height = index + steps;
|
||||
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
|
||||
for next_to_check in 1..=steps {
|
||||
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
|
||||
continue;
|
||||
}
|
||||
visted_indices = to_add;
|
||||
next_nodes.push((to_add, nums[to_add as usize]));
|
||||
greatest_visted_indices = to_add;
|
||||
next_nodes.push_front((to_add, nums[to_add as usize]));
|
||||
}
|
||||
}
|
||||
false
|
||||
|
|
Loading…
Add table
Reference in a new issue