463. 岛屿的周长
js
;(function () {
/**
* 463. 岛屿的周长
*
*/
function islandPerimeter(grid: number[][]): number {
// 方法一:
let res: number = 0
for (let i = 0; i < grid.length; i++) {
// 计算所有岛屿格子数
let count: number = 0
// 计算上下重叠的格子数
let isOverlapping: number = 0
// 计算左右不重叠的格子数
let lrCount: number = 0
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === 1) {
count !== 0 && grid[i][j - 1] === 0 && lrCount++
count++
}
if (i > 0) {
grid[i][j] && grid[i - 1][j] && isOverlapping++
}
}
if (count > 0) {
res += count * 2 + 2
// 还需要减去重叠的边。每重叠 N 个格子,就要去掉 2N 条边
res -= isOverlapping * 2
res += lrCount * 2
// console.log('Count: ', count)
// console.log('isOverlapping: ', isOverlapping)
// console.log('lrCount: ', lrCount)
}
}
return res
}
let grid = [
[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]
]
let grid2 = [[1]]
let grid3 = [[1, 0]]
let grid4 = [[1], [0]]
let grid5 = [
[1, 1, 1],
[1, 0, 1]
]
console.log(islandPerimeter(grid))
console.log(islandPerimeter(grid2))
console.log(islandPerimeter(grid3))
console.log(islandPerimeter(grid4))
console.log(islandPerimeter(grid5))
})()