Created
April 18, 2024 16:26
-
-
Save tatsuyax25/33a14fe3b8d0f885e278d2e434d5f971 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} grid | |
* @return {number} | |
*/ | |
var islandPerimeter = function(grid) { | |
// Initialize perimeter to 0 | |
var perimeter = 0; | |
// Loop through each cell in the grid | |
for (var i = 0; i < grid.length; i++) { | |
for (var j = 0; j < grid[i].length; j++) { | |
// If the cell is land (1) | |
if (grid[i][j] === 1) { | |
// Add 4 to the perimeter (assuming it's a standalone cell) | |
perimeter += 4; | |
// If there's a cell above this one and it's also land, subtract 2 from the perimeter | |
// (because this cell shares an edge with the one above it) | |
if (i > 0 && grid[i - 1][j] === 1) { | |
perimeter -= 2; | |
} | |
// If there's a cell to the left of this one and it's also land, subtract 2 from the perimeter | |
// (because this cell shares an edge with the one to its left) | |
if (j > 0 && grid[i][j - 1] === 1) { | |
perimeter -= 2; | |
} | |
} | |
} | |
} | |
// Return the calculated perimeter | |
return perimeter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment