题目:
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)走到某个坚果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]);
}
};