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

程序IT圈

共 1239字,需浏览 3分钟

 ·

2022-04-11 11:54

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

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

示例



解题

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:另一棵树的子树

浏览 46
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报