Skip to content
RED SAGSkills
easy15 ptsmatrix

Coastline Length of the Land

A map is a grid of 1 (land) and 0 (water). Every cell is a unit square. Cells outside the grid are water.

Return the total length of coastline: the number of unit edges where a land cell touches water or the edge of the map.

Example 1

Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16

Example 2

Input: grid = [[1]]
Output: 4
Explanation: A single square has four sides.

Constraints

  • 1 <= rows, cols <= 150
  • grid[r][c] is 0 or 1
Hint 1

Each land cell contributes 4 edges.

Hint 2

Every pair of adjacent land cells hides 2 of those edges.

Good practice for: Game Developer, Frontend Developer, Mobile App Developer, Data Scientist, Embedded Systems Engineer

Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.