Skip to main content

463.js

/** ------------------------------------------------------------------------------
*
* 463. Island Perimeter
* Topics: Matrix
* https://leetcode.com/problems/island-perimeter/?envType=problem-list-v2&envId=matrix
*
------------------------------------------------------------------------------ */
/**
* @param {number[][]} grid
* @return {number}
*/
var islandPerimeter = function (grid) {
const row = grid.length
const col = grid[0].length

let count = 0

for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (grid[i][j] === 0) continue

count += 4
if (j > 0 && grid[i][j - 1]) {
count -= 2
}
if (i > 0 && grid[i - 1][j]) {
count -= 2
}
}
}
return count
}

console.log(
islandPerimeter([
[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
]),
)