Description:
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.
思路:
刚拿到这道题把题目看懂后,不知道如何分析这个问题。第一时间想到的是 BFS和DP,可是不知道如何切入。
这个时候分析问题就要逆向思考,松鼠去找坚果,然后运到树。逆向思考的意思是说,不如让坚果去找树,坚果去找松鼠。
另外假定一些特殊清况,如果松鼠本来就在树那里,那么要做的事情就是,把某个坚果找到并运回,也就是某个坚果到树“距离”的两倍。但是松鼠初始位置不一定在树那,松鼠一旦运好第一个坚果,后面都是从树出发的操作。所以松鼠运第一个坚果的选取,决定了路径的最小值,也就是把某个松鼠–>坚果 替换 坚果 –> 树。
Code:
public class Solution {
public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
int n = nuts.length;
int[] nutToTree = new int[n];
int[] nutToSquirrel = new int[n];
int sum = 0;
for (int i = 0; i < n; i++){
nutToTree[i] = Math.abs(nuts[i][0] - tree[0]) + Math.abs(nuts[i][1] - tree[1]);
sum += nutToTree[i] * 2;
nutToSquirrel[i] = Math.abs(nuts[i][0] - squirrel[0]) + Math.abs(nuts[i][1] - squirrel[1]);
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int dist = sum + nutToSquirrel[i] - nutToTree[i];
min = Math.min(min, dist);
}
return min;
}
}