573. Squirrel Simulation

Problem statement:

There's a tree, a squirrel, and several nuts. Positions are represented by the cells in a 2D grid. Your goal is to find the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one. 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. The distance is represented by the number of moves.

Example 1:

Input: 
Height : 5
Width : 7
Tree position : [2,2]
Squirrel : [4,4]
Nuts : [[3,0], [2,5]]
Output: 12
Explanation:

Note:

  1. All given positions won't overlap.
  2. The squirrel can take at most one nut at one time.
  3. The given positions of nuts have no order.
  4. Height and width are positive integers. 3 <= height * width <= 10,000.
  5. The given positions contain at least one nut, only one tree and one squirrel.

Solution:

There is a matrix, it looks like BFS, DFS or DP, however, there is only some numbers, there is no any input board or matrix. So it is pure math.

The key is which nut as the first target for the squirrel to pick.
Frist, calculate the distance from squirrel and trees to all nuts, put them in two different arrays, and accumulate the total distance from tree to nuts.
The final step to find the solution. Loop to pick each nut as the first target. Subtract the distance from tree to this nuts and plus the distance from this nut to the squirrel, and choose the minimal distance.

The time complexity is O(n).

class Solution {
public:
    int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int>>& nuts) {
        vector<int> squi2nuts;
        vector<int> tree2nuts;
        int total_dis = 0;
        for(int i = 0; i < nuts.size(); i++){
            // calculate the distrance from squirrel to nuts
            squi2nuts.push_back(abs(nuts[i][0] - squirrel[0]) + abs(nuts[i][1] - squirrel[1]));
            // calculate total distance, double the distance from tree to all nuts
            total_dis += (abs(nuts[i][0] - tree[0]) + abs(nuts[i][1] - tree[1])) * 2;
            // calculate the distrance from tree to nuts
            tree2nuts.push_back(abs(nuts[i][0] - tree[0]) + abs(nuts[i][1] - tree[1]));
        }
        int min_dis = INT_MAX;
        for(int i = 0; i < tree2nuts.size(); i++){
            min_dis = min(min_dis, total_dis - tree2nuts[i] + squi2nuts[i]);
        }
        return min_dis;
    }
};
原文地址:https://www.cnblogs.com/wdw828/p/6823655.html