如下二维数组代表一个棋盘中的每个格子,其中0标识被墨水污染的格子,1标识干净的格子,由于相邻的墨水会合并成一滴墨水,如下所示代表棋盘上有3滴墨水。
[
[1,0,1,1,1,1],
[1,1,1,1,0,1],
[1,1,1,1,0,0],
[1,1,0,1,1,1],
[1,1,0,1,1,1],
[1,1,1,1,1,1],
]
请编程计算棋盘上有几滴墨水。
解:
const arr = [
[1, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 0, 0],
[1, 1, 0, 1, 1, 1],
[1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
]
let count = 0
for (let y = 0; y < arr.length; y++) {
for (let x = 0; x < arr[0].length; x++) {
const current = arr[y][x]
const up = arr[y - 1] !== undefined ? arr[y - 1][x] : undefined
const left = arr[y][x - 1]
if (current === 0 && up !== 0 && left !== 0) {
count++
}
}
}
console.log(count)