source: https://leetcode.com/problems/squirrel-simulation/

## Table of Contents

# Squirrel Simulation

## Description

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.

## Example 1

**Input:** height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]**Output:** 12**Explanation:** The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.

## Example 2

**Input:** height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]**Output:** 3

## Constraints

- 1 <= height, width <= 100
- tree.length == 2
- squirrel.length == 2
- 1 <= nuts.length <= 5000
- nuts[i].length == 2
- 0 <= treer, squirrelr, nutir <= height
- 0 <= treec, squirrelc, nutic <= width

## Solution

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class Solution { public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { int[] treeDist = new int[nuts.length]; int[] totalDist = new int[nuts.length]; int sx = squirrel[0]; int sy = squirrel[1]; int tx = tree[0]; int ty = tree[1]; int sum = 0; for(int i=0;i<nuts.length;i++){ treeDist[i] = distance(tx, ty, nuts[i][0], nuts[i][1]); totalDist[i] = distance(sx, sy, nuts[i][0], nuts[i][1]) + treeDist[i]; sum += treeDist[i]*2; } int minDist = Integer.MAX_VALUE; for(int i=0;i<treeDist.length;i++){ int dist = sum - 2 * treeDist[i] + totalDist[i]; if(dist < minDist){ minDist = dist; } } return minDist; } private int distance(int x1, int y1, int x2, int y2){ return Math.abs(x1-x2) + Math.abs(y1-y2); } } |