​LeetCode刷题实战573:松鼠模拟

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 松鼠模拟,我们先来看题面:

https://leetcode-cn.com/problems/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.

现在有一棵树,一只松鼠和一些坚果。位置由二维网格的单元格表示。你的目标是找到松鼠收集所有坚果的最小路程,且坚果是一颗接一颗地被放在树下。松鼠一次最多只能携带一颗坚果,松鼠可以向上,向下,向左和向右四个方向移动到相邻的单元格。移动次数表示路程。

示例

49a1ce3cffb4d638cfa99fb8cd7bc26d.png


解题

https://blog.csdn.net/weixin_44171872/article/details/108985656

主要思路:

(1)将每个坚果取回到树上,则需要松鼠从树上出发,取到坚果,再返回到树,这个距离其实就是树和坚果作为对角线之间的矩形的宽高之和;

(2)则可以先将所有的坚果到树的距离统计出来;

(3)考虑到松鼠起始位置并不在树上,故松鼠第一次取的坚果可能导致总的路程不一致,存在最短距离,故可以针对每个坚果作为松鼠第一个要取的坚果,来计算此时的距离,这个过程中保存最小值即可;

class Solution {
public:
    int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int>>& nuts) {
        int sum_nums=0;
        //先统计出所有坚果的距离
        for(vector<int>&nut:nuts){
            sum_nums+=abs(nut[0]-tree[0])+abs(nut[1]-tree[1]);
        }
        sum_nums<<=1;
        int res=INT_MAX;
        //针对每个坚果作为松鼠要取的第一个坚果,计算各个距离,并保存最小的距离
        for(vector<int>&nut:nuts){
            res=min(res,sum_nums-(abs(nut[0]-tree[0])+abs(nut[1]-tree[1]))+(abs(nut[0]-squirrel[0])+abs(nut[1]-squirrel[1])));
        }
        return res;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-560题汇总,希望对你有点帮助!

LeetCode刷题实战561:数组拆分 I

LeetCode刷题实战562:矩阵中最长的连续1线段

LeetCode刷题实战563:二叉树的坡度

LeetCode刷题实战564:寻找最近的回文数

LeetCode刷题实战565:数组嵌套

LeetCode刷题实战566:重塑矩阵

LeetCode刷题实战567:字符串的排列

LeetCode刷题实战568:最大休假天数

LeetCode刷题实战569:员工薪水中位数

LeetCode刷题实战570:至少有5名直接下属的经理

LeetCode刷题实战571:给定数字的频率查询中位数

LeetCode刷题实战572:另一棵树的子树

395a1bc1bbd712bd7ff95e6e2a8be609.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值