1306. 跳跃游戏 III
This commit is contained in:
parent
6e59cabd84
commit
afa91fe380
68
src/main.rs
68
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>) -> i32 {
|
||||
let mut mp = HashMap::new();
|
||||
for i in 0..arr.len() {
|
||||
mp.entry(arr[i])
|
||||
.and_modify(|x: &mut Vec<usize>| x.push(i))
|
||||
.or_insert(vec![i]);
|
||||
pub fn can_reach(arr: Vec<i32>, 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<bool>, 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));
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue