[Leetcode] 573. Squirrel Simulation 解题报告

来源:互联网 发布:apache tomcat怎么用 编辑:程序博客网 时间:2024/06/05 16:20

题目

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 : 5Width : 7Tree position : [2,2]Squirrel : [4,4]Nuts : [[3,0], [2,5]]Output: 12Explanation:

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]);    }};

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 风电板块 氟化工板块 601板块 太平洋板块 热门板块 板块与板块的交界处 融资融券板块 人力资源板块 互联网金融板块 通信设备板块 电气设备板块 地球板块分布图 计算机应用板块 生物医药板块 化学制药板块 世界板块分布图 房地产开发板块 智能穿戴板块 新能源汽车板块 饮料制造板块 汽车零部件板块 文化传媒板块 手抄报板块设计图 地球板块漂移 国产软件板块 网络安全板块 建筑装饰板块 集成电路板块 通信服务板块 电子制造板块 欧亚大陆板块 在线教育板块 次新股板块股票 股票板块代码 石油板块股票 生物板块股票 电子板块股票 金属板块股票 科技板块有哪些股票 电子板块股票有哪些 房地产板块龙头股