#573
Medium Algorithms Squirrel simulation
Array Math
57.3% acceptance
Mar 31, 2026
420
40
You are given two integers height and width representing a garden of size height x width. You are also given:
an array tree where tree = [treer, treec] is the position of the tree in the garden,
an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden,
and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden.
The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.
Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one.
The distance is the number of moves.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_distance(height: i32, width: i32, tree: Vec<i32>, squirrel: Vec<i32>, nuts: Vec<Vec<i32>>) -> i32 {
let total_dist: i32 = nuts.iter().map(|n| {
2 * ((n[0] - tree[0]).abs() + (n[1] - tree[1]).abs())
}).sum();
let mut min_save = i32::MAX;
for n in &nuts {
let d_tree = (n[0] - tree[0]).abs() + (n[1] - tree[1]).abs();
let d_sq = (n[0] - squirrel[0]).abs() + (n[1] - squirrel[1]).abs();
min_save = min_save.min(d_sq - d_tree);
}
total_dist + min_save
}
}