From afa91fe380eaa70d04957372d2fd1675c94d1eb5 Mon Sep 17 00:00:00 2001 From: li_chx Date: Mon, 18 May 2026 17:00:02 +0800 Subject: [PATCH] =?UTF-8?q?1306.=20=E8=B7=B3=E8=B7=83=E6=B8=B8=E6=88=8F=20?= =?UTF-8?q?III?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 68 +++++++++++++++++++++++------------------------------ 1 file changed, 30 insertions(+), 38 deletions(-) diff --git a/src/main.rs b/src/main.rs index 7cf4a89..5abbd11 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,57 +1,49 @@ mod arr; struct Solution {} -use std::collections::hash_map::Entry; -use std::collections::{HashMap, VecDeque}; +use std::collections::VecDeque; impl Solution { - pub fn min_jumps(arr: Vec) -> i32 { - let mut mp = HashMap::new(); - for i in 0..arr.len() { - mp.entry(arr[i]) - .and_modify(|x: &mut Vec| x.push(i)) - .or_insert(vec![i]); + pub fn can_reach(arr: Vec, start: i32) -> bool { + let start = start as usize; + if arr[start] == 0 { + return true; } let mut depth = vec![arr.len() as i32 + 1; arr.len()]; - depth[arr.len() - 1] = 0; + depth[start] = 0; let mut queue = VecDeque::new(); let mut inserted = vec![false; arr.len()]; - inserted[arr.len() - 1] = true; - queue.push_back(arr.len() - 1); + inserted[start] = true; + queue.push_back(start); while let Some(x) = queue.pop_front() { - if x > 0 { - if !inserted[x - 1] { - depth[x - 1] = depth[x] + 1; - queue.push_back(x - 1); - inserted[x - 1] = true; - } - } - if x + 1 < arr.len() { - if !inserted[x + 1] { - depth[x + 1] = depth[x] + 1; - queue.push_back(x + 1); - inserted[x + 1] = true; - } - } - if let Entry::Occupied(arr) = mp.entry(arr[x]) { - for y in arr.get() { - if !inserted[*y] { - depth[*y] = depth[x] + 1; - queue.push_back(*y); - inserted[*y] = true; + let y = x + arr[x] as usize; + let mut func = |inserted: &mut Vec, y: usize| -> bool { + if !inserted[y] { + depth[y] = depth[x] + 1; + queue.push_back(y); + (*inserted)[y] = true; + if arr[y] == 0 { + return true; } } + return false; + }; + if y < arr.len() { + if func(&mut inserted, y) { + return true; + } } - if inserted[0] { - return depth[0]; + let y = x as i32 - arr[x]; + if y >= 0 { + let y = y as usize; + if func(&mut inserted, y) { + return true; + } } } - -1 + false } } fn main() { - println!( - "{:?}", - Solution::min_jumps(vec![100, -23, -23, 404, 100, 23, 23, 23, 3, 404]) - ); + println!("{:?}", Solution::can_reach(vec![4, 2, 3, 0, 3, 1, 2], 5)); }