[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.

思路:

由于松鼠每次只能走一个单位,而且每次只能带一个坚果到树下,那么除了第一个要捡的坚果外,从树出发,捡其他每一个

坚果的距离都要乘以2(从树到坚果i的距离 +从坚果i到树的距离)。

不妨认为捡每一个坚果都是从树出发,那么最终的距离:

dis = 2*(所有getDis(tree,nut[i])的和) - getDis(tree[i],nut[i])) + getDis(squireel,nut[i])
 int getDis(vector<int>& a,vector<int>& b)
 {
     return abs(a[0] - b[0]) + abs(a[1] - b[1]);
 }
int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int> >& nuts)
{
    //dis = 2*(所有getDis(tree,nut[i])) - getDis(tree,nut[i])) + getDis(squireel,nut[i])
    int tempdis = 0;
     int distance = 1000000;
    for(int i=0;i<nuts.size();i++)
    {
         tempdis += 2*getDis(tree,nuts[i]);
    }
    for(int i=0;i<nuts.size();i++)
    {
         int distanceTemp = tempdis - getDis(tree,nuts[i]) + getDis(squirrel,nuts[i]);
         if(distance >distanceTemp) distance = distanceTemp;
    }
    return distance;
}

 

转载于:https://www.cnblogs.com/hellowooorld/p/6820396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值