Skip to content

Latest commit

 

History

History

573

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Companies:
Square

Related Topics:
Array, Math

Solution 1.

Assume we have 2 nuts, n1, n2. Their distances to the tree are a and b respectively, and their distances to the squirrel are sa, sb respectively.

If we go to n1 first then n2, the total distance is sa + a + 2b = 2*(a+b) + (sa-a).

If we go to n2 first then n1, the total distance is 2a + sb + b = 2*(a+b) + (sb-b).

So, we just need to compute a+b and the minimum value of sa-a and sb-b.

Generally, we need to compute the sum of distances between each nut and the tree, and find the minimum value of {squirrel nut distance} - {tree nut distance}.

// OJ: https://leetcode.com/problems/squirrel-simulation/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
    int dist(vector<int> &a, vector<int> &b) {
        return abs(a[0] - b[0]) + abs(a[1] - b[1]);
    }
public:
    int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int>>& nuts) {
        int sum = 0, mn = INT_MAX;
        for (auto &n : nuts) {
            sum += dist(tree, n);
            mn = min(mn, dist(squirrel, n) - dist(tree, n));
        }
        return 2 * sum + mn;
    }
};