Это абстрактный подход. Вы можете взять счетчик островов и посчитать предметы каждого острова.
function check(array) {
function test(array, i, j, value) {
if (array[i] && array[i][j] === -1) {
count[value] = (count[value] || 0) + 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,
count = {};
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++));
array.map(a => console.log(...a));
return count;
}
console.log(check([[1, 0, 1], [1, 0, 0], [1, 1, 1]]));
console.log(check([[1, 0, 1], [0, 1, 0], [1, 0, 1]]));
console.log(check([[1, 0, 0, 1, 1], [1, 1, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1], [1, 1, 1, 0, 1]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }