Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. [[0,1,0,0],
  2. [1,1,1,0],
  3. [0,1,0,0],
  4. [1,1,0,0]]
  5.  
  6. /**
  7. * @param {number[][]} grid
  8. * @return {number}
  9. */
  10. var islandPerimeter = function(grid) {
  11. const getWaterNeighborAt = position => {
  12. if (!grid[position.y][position.x]) { return 0; }
  13.  
  14. const north = position.y - 1 < 0 ? true : grid[position.y - 1][position.x] === 0;
  15. const east = position.x + 1 >= grid[0].length ? true : grid[position.y][position.x + 1] === 0;
  16. const south = position.y + 1 >= grid.length ? true : grid[position.y + 1][position.x] === 0;
  17. const west = position.x - 1 < 0 ? true : grid[position.y][position.x - 1] === 0;
  18.  
  19. return north + east + south + west;
  20. };
  21. let perimeter = 0;
  22. grid.forEach((row, y) => {
  23. row.forEach((_, x) => {
  24. perimeter += getWaterNeighborAt({x, y});
  25. });
  26. });
  27. return perimeter;
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement