[LeetCode]Squirrel Simulation

题目描述:

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.

题目大意:

二维格子高度height,宽度width。其中包含一棵树tree,一个松鼠squirrel,以及一些坚果nuts。

求松鼠将所有坚果运送至树的位置所需的最小距离之和。

注意:

  1. 所有位置不会重叠
  2. 松鼠一次运送只能携带一枚坚果
  3. 给定坚果位置是无序的
  4. 高度和宽度是正整数,并且 3 <= height * width <= 10,000
  5. 给定位置包含至少一枚坚果,只有一棵树和一只松鼠

解题思路:

求所有坚果到树的曼哈顿距离之和的2倍,记为total

求松鼠到坚果的曼哈顿距离 - 树到坚果曼哈顿距离的最小值, 该值与total之和即为最终答案

Python代码:

class Solution(object):
    def minDistance(self, height, width, tree, squirrel, nuts):
        """
        :type height: int
        :type width: int
        :type tree: List[int]
        :type squirrel: List[int]
        :type nuts: List[List[int]]
        :rtype: int
        """
        manhattan = lambda p, q: abs(p[0] - q[0]) + abs(p[1] - q[1])
        total = 2 * sum(manhattan(tree, nut) for nut in nuts)
        return total + min(manhattan(squirrel, nut) - manhattan(tree, nut) for nut in nuts)

 

本文链接:http://bookshadow.com/weblog/2017/05/07/leetcode-squirrel-simulation/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论