1306. 跳跃游戏 III
This commit is contained in:
parent
6e59cabd84
commit
afa91fe380
64
src/main.rs
64
src/main.rs
|
|
@ -1,57 +1,49 @@
|
||||||
mod arr;
|
mod arr;
|
||||||
|
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
use std::collections::hash_map::Entry;
|
use std::collections::VecDeque;
|
||||||
use std::collections::{HashMap, VecDeque};
|
|
||||||
|
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn min_jumps(arr: Vec<i32>) -> i32 {
|
pub fn can_reach(arr: Vec<i32>, start: i32) -> bool {
|
||||||
let mut mp = HashMap::new();
|
let start = start as usize;
|
||||||
for i in 0..arr.len() {
|
if arr[start] == 0 {
|
||||||
mp.entry(arr[i])
|
return true;
|
||||||
.and_modify(|x: &mut Vec<usize>| x.push(i))
|
|
||||||
.or_insert(vec![i]);
|
|
||||||
}
|
}
|
||||||
let mut depth = vec![arr.len() as i32 + 1; arr.len()];
|
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 queue = VecDeque::new();
|
||||||
let mut inserted = vec![false; arr.len()];
|
let mut inserted = vec![false; arr.len()];
|
||||||
inserted[arr.len() - 1] = true;
|
inserted[start] = true;
|
||||||
queue.push_back(arr.len() - 1);
|
queue.push_back(start);
|
||||||
while let Some(x) = queue.pop_front() {
|
while let Some(x) = queue.pop_front() {
|
||||||
if x > 0 {
|
let y = x + arr[x] as usize;
|
||||||
if !inserted[x - 1] {
|
let mut func = |inserted: &mut Vec<bool>, y: usize| -> bool {
|
||||||
depth[x - 1] = depth[x] + 1;
|
if !inserted[y] {
|
||||||
queue.push_back(x - 1);
|
depth[y] = depth[x] + 1;
|
||||||
inserted[x - 1] = true;
|
queue.push_back(y);
|
||||||
|
(*inserted)[y] = true;
|
||||||
|
if arr[y] == 0 {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if x + 1 < arr.len() {
|
return false;
|
||||||
if !inserted[x + 1] {
|
};
|
||||||
depth[x + 1] = depth[x] + 1;
|
if y < arr.len() {
|
||||||
queue.push_back(x + 1);
|
if func(&mut inserted, y) {
|
||||||
inserted[x + 1] = true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Entry::Occupied(arr) = mp.entry(arr[x]) {
|
let y = x as i32 - arr[x];
|
||||||
for y in arr.get() {
|
if y >= 0 {
|
||||||
if !inserted[*y] {
|
let y = y as usize;
|
||||||
depth[*y] = depth[x] + 1;
|
if func(&mut inserted, y) {
|
||||||
queue.push_back(*y);
|
return true;
|
||||||
inserted[*y] = true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if inserted[0] {
|
false
|
||||||
return depth[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn main() {
|
fn main() {
|
||||||
println!(
|
println!("{:?}", Solution::can_reach(vec![4, 2, 3, 0, 3, 1, 2], 5));
|
||||||
"{:?}",
|
|
||||||
Solution::min_jumps(vec![100, -23, -23, 404, 100, 23, 23, 23, 3, 404])
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue