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:
- All given positions won't overlap.
- The squirrel can take at most one nut at one time.
- The given positions of nuts have no order.
- Height and width are positive integers. 3 <= height * width <= 10,000.
- The given positions contain at least one nut, only one tree and one squirrel.
1、题目描述
现在有一棵树,一只松鼠和一些坚果。位置由二维网格的单元格表示。你的目标是找到松鼠收集所有坚果的最小路程,且坚果是一颗接一颗地被放在树下。松鼠一次最多只能携带一颗坚果,松鼠可以向上,向下,向左和向右四个方向移动到相邻的单元格。移动次数表示路程。
输入 1:
输入:
高度 : 5
宽度 : 7
树的位置 : [2,2]
松鼠 : [4,4]
坚果 : [[3,0], [2,5]]
输出: 12
解释:
注意:
- 所有给定的位置不会重叠。
- 松鼠一次最多只能携带一颗坚果。
- 给定的坚果位置没有顺序。
- 高度和宽度是正整数。
3 <= 高度 * 宽度 <= 10,000
。
- 给定的网格至少包含一颗坚果,唯一的一棵树和一只松鼠。
2、解题思路
- 松鼠从初始位置先到一个坚果的位置,然后回到树
- 剩余的坚果都是从树上去,然后回到树上,就是
2
倍的曼哈顿距离
- 只需要找到第一步,也就是松鼠先去拿的坚果,然后回到树上这一步所有的距离对整体的步数减少效果最明显的一个即可
Difficulty:
Medium
Lock:
Prime