https://leetcode.com/problems/island-perimeter/description/?envType=daily-question&envId=2024-04-18
/** * @param {number[][]} grid * @return {number} */
var islandPerimeter = function(grid) { const rows = grid.length const cols = grid[0].length let perimeter = 0 const isWater = (r, c) => { return r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === 0 } for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (grid[r][c] === 1) { if (isWater(r - 1, c)) perimeter++ if (isWater(r + 1, c)) perimeter++ if (isWater(r, c - 1)) perimeter++ if (isWater(r, c + 1)) perimeter++ } } } return perimeter };
Discover more from Coursity
Subscribe to get the latest posts sent to your email.