← Back to challenges

Land Perimeter

JavaScriptHardarraysconditionslanguage_fundamentalsloops

Instructions

The function is given a map with 1 representing land, 0 representing water. A land cell can have four neighbors along its edges. Compute the total perimeter of shore-lines that are defined by land cells touching water or the outer edges of the map. Each cell edge has a length equal to 1. An isolated cell without neighbors has a total perimeter length of 4.

Examples

islandsPerimeter([
  [0, 1, 0, 0],
  [1, 1, 1, 0],
  [0, 1, 0, 0],
  [1, 1, 0, 0]
]) ➞ 16
islandsPerimeter([
  [1, 1, 1, 1, 1, 1],
  [1, 0, 0, 0, 0, 1],
  [1, 0, 1, 1, 0, 1],
  [1, 0, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1],
]), 42)
islandsPerimeter([
  [1, 0]
]) ➞ 4

Notes

N/A

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.