题目描述:有一棵树,一只松鼠和几个坚果。位置由二维网格中的单元格表示。你的目标是找到最短
的距离,让松鼠收集所有的坚果,并把它们一个一个地放在树下。松鼠一次只能最多吃一个坚果
,可以在四个方向上移动——上、下、左、右,到相邻的细胞。距离用移动的次数表示。
样例
给定高度= 5
,width = 7
, treePosition = [2,2]
, squirrel =[4,4]
,螺母= [[3,0], [2,5]]
,
返回 12.
思路
解法一:
移动距离最短的路线中,只有第一个点是从松鼠位置到第一个点的位置然后到树的位置,其他每个点的路线都是从树到点然后到树,现在的目的就是选取第一个点,遍历螺母数组,因为第一个点不同的两条路线,只有两段不重复的路径,选取最小值,即可找到第一个点。
/**
* @param height: the height
* @param width: the width
* @param tree: the position of tree
* @param squirrel: the position of squirrel
* @param nuts: the position of nuts
* @return: the minimal distance
*/
const minDistance = function (height, width, tree, squirrel, nuts) {
let rows = nuts.length;
let index;
let dist1, dist2, dist3, dist4, tag;
for (let i = 0; i < rows; i++) {
tag = 1;
index = i;
for (j = i + 1; j < rows; j++) {
dist1 = Math.abs(nuts[i][0] - squirrel[0]) + Math.abs(nuts[i][1] - squirrel[1]);
dist2 = Math.abs(nuts[i][0] - tree[0]) + Math.abs(nuts[i][1] - tree[1]);
dist3 = Math.abs(nuts[j][0] - squirrel[0]) + Math.abs(nuts[j][1] - squirrel[1]);
dist4 = Math.abs(nuts[j][0] - tree[0]) + Math.abs(nuts[j][1] - tree[1]);
if (dist1 + dist4 > dist3 + dist2) {
tag = 0;
break;
}
}
if (tag == 1 || i == rows - 1)
break;
}
let res = 0;
for (i = 0; i < rows; i++) {
if (i == index) {
res += Math.abs(nuts[i][0] - squirrel[0]) + Math.abs(nuts[i][1] - squirrel[1]) +
Math.abs(nuts[i][0] - tree[0]) + Math.abs(nuts[i][1] - tree[1]);
}
else {
res += 2 * (Math.abs(nuts[i][0] - tree[0]) + Math.abs(nuts[i][1] - tree[1]));
}
}
return res;
}
解法二:
/**
* @param height: the height
* @param width: the width
* @param tree: the position of tree
* @param squirrel: the position of squirrel
* @param nuts: the position of nuts
* @return: the minimal distance
*/
const minDistance = function (height, width, tree, squirrel, nuts) {
const calcDist = (a, b) => {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}
let rows = nuts.length;
let dist1, dist2, dist3, dist4;
let tag, index;
for(let i = 0; i < rows; i++) {
tag = 1;
index = i;
for(let j = i + 1; j < rows; j++) {
dist1 = calcDist(nuts[i], squirrel);
dist2 = calcDist(nuts[i], tree);
dist3 = calcDist(nuts[j], squirrel);
dist4 = calcDist(nuts[j], tree);
if(dist1 + dist4 > dist3 + dist2) {
tag = 0;
break;
}
}
if(tag || i == rows - 1)
break;
}
let res = 0;
for(i = 0; i < rows; i++) {
if(i == index) {
res += calcDist(nuts[i], squirrel) + calcDist(nuts[i], tree);
}
else
res += 2 * calcDist(nuts[i], tree);
}
return res;
}