js代码 曼哈顿距离 给出一张m×n的地图map.map中仅有2个1.和若干个0.使用数组的索引作为坐标,计算出这两个1的曼哈顿距离 曼哈顿距离=|x0-x1|+|y0-y1|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 案例一 结果:4
let map = [
[1, 0, 0],
[0, 0, 0],
[0, 0, 1],
];
// 案例二 结果:1
let map1 = [
[0, 0, 0, 0],
[0, 0, 1, 1],
];
function maparr(arr) {
let result = [];
arr.forEach((item, index) => {
item.forEach((zitem, zindex) => {
if (zitem == 1) {
result.push({
x: index,
y: zindex
})
}
});
})
return result.reduce((current, item) => {
return Math.abs(current.y - item.y) + Math.abs(current.x - item.x)
})
}
console.log('map', maparr(map));
console.log('map1', maparr(map1));
</script>
</body>
</html>
曼哈顿算法公式_JavaScript实现数学公式
https://blog.csdn.net/weixin_42517807/article/details/112193495