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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值