1. 程式人生 > >[leetcode-573-Squirrel Simulation]

[leetcode-573-Squirrel Simulation]

static under amp min ger 由於 cnblogs stat down

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

[leetcode-573-Squirrel Simulation]