Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [[0,1,0,0],
- [1,1,1,0],
- [0,1,0,0],
- [1,1,0,0]]
- /**
- * @param {number[][]} grid
- * @return {number}
- */
- var islandPerimeter = function(grid) {
- const getWaterNeighborAt = position => {
- if (!grid[position.y][position.x]) { return 0; }
- const north = position.y - 1 < 0 ? true : grid[position.y - 1][position.x] === 0;
- const east = position.x + 1 >= grid[0].length ? true : grid[position.y][position.x + 1] === 0;
- const south = position.y + 1 >= grid.length ? true : grid[position.y + 1][position.x] === 0;
- const west = position.x - 1 < 0 ? true : grid[position.y][position.x - 1] === 0;
- return north + east + south + west;
- };
- let perimeter = 0;
- grid.forEach((row, y) => {
- row.forEach((_, x) => {
- perimeter += getWaterNeighborAt({x, y});
- });
- });
- return perimeter;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement