[Leetcode] 573. Squirrel Simulation 解题报告

题目

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.

思路

松鼠的行为可以分为两个步骤:1)走到某个坚果i那里,然后把坚果i移动到树下;2)依次走到其它坚果那里,带上坚果之后返回来。所以松鼠的最短行程只取决于第一次选择哪个坚果,这是因为选择坚果i之后,松鼠需要额外走从它当前位置到坚果i的距离,但是却可以省下从树到坚果i之间的距离,所以我们的目标就是找到i,使得distance(squireel, nuts[i]) - distance(tree, nuts[i])最小。确定i之后,再按照松鼠的移动轨迹计算路程即可。

代码

class Solution {
public:
    int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int>>& nuts) {
        int min_dist = INT_MAX, min_index = -1, ret = 0, dist;
        for (int i = 0; i < nuts.size(); ++i) {
            dist = distance(squirrel, nuts[i]) - distance(nuts[i], tree);
            if (dist < min_dist) {
                min_dist = dist;
                min_index = i;
            }
        }
        ret += min_dist;
        for (int i = 0; i < nuts.size(); ++i) {
            ret += 2 * distance(nuts[i], tree);
        }
        return ret;
    }
private:
    int distance(vector<int> &from, vector<int> &to) {
        return abs(from[0] - to[0]) + abs(from[1] - to[1]);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值