岛数二维数组算法 [英] island count two-dimensional array algorithm
本文介绍了岛数二维数组算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
let arr = [[1, 0, 1],
[1, 0, 0],
[1, 1, 1]
];
我有一个数组,其中 1 个岛和 0 个水.我需要写一个岛屿计数器.这里有 2 个岛 1 个大和 1 个小(单个).例如这里有 5 个单岛
i have array where 1-island and 0-water. I need to write a island counter. Here are 2 island 1 big and 1 small(singele). For example here are 5 single islands
let arr = [[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
];
我写了双循环来上诉数组中的每个项目,如下所示:
i had write double cycle to appeal each item in array like this:
for(let i = 0; i < arr.length; i++){
for(let x = 0; x < arr[i].length; x++){
if(...){}
}
}
我需要为此写一个条件.请帮帮我.
and I need to write сondition for this. Help me please.
推荐答案
您可以使用计数器并检查所有相邻项目并使用实际计数器更新元素.
You could use a counter and check all adjacent items and update the element with the actual counter.
function check(array) {
function test(array, i, j, value) {
if (array[i] && array[i][j] === -1) {
array[i][j] = value;
test(array, i -1, j, value);
test(array, i + 1, j, value);
test(array, i, j - 1, value);
test(array, i, j + 1, value);
return true;
}
}
var value = 1;
array.forEach(a=> a.forEach((b, i, bb) => bb[i] = -b));
array.forEach((a, i, aa) => a.forEach((b, j) => test(aa, i, j, value) && value++));
document.getElementById('out').innerHTML += array.map(a => a.join(' ')).join('\n') + '<hr>';
return value - 1;
}
console.log(check([[1, 0, 1], [1, 0, 0], [1, 1, 1]]));
console.log(check([[1, 0, 1], [0, 1, 0], [1, 0, 1]]));
<pre id="out"></pre>
这篇关于岛数二维数组算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文