Island Perimeter
easySave
ArrayDepth-First SearchMatrix
You are given a grid map of '1's (land) and '0's (water). Return the perimeter of the island formed by the land by counting the number of sides of '1's that are adjacent to '0's or at the boundaries of the grid.
Example 1
Input
[ [ 0, 1, 0, 0 ], [ 1, 1, 1, 0 ], [ 0, 1, 0, 0 ], [ 1, 1, 0, 0 ] ]
Output
14
Explanation. The island "1s" have 14 sides next to water or outside the grid boundary.
Example 2
Input
[ [ 1 ] ]
Output
4
Explanation. A single '1' has all four sides contributing to the perimeter.
Example 3
Input
[ [ 1, 0, 1 ], [ 0, 1, 0 ], [ 1, 0, 1 ] ]
Output
12
Explanation. Each land tile has separate sides exposed to water or boundary, totaling 12.
Follow-up: Can you implement the solution in a more optimal way using DFS or BFS algorithm?
Constraints:
The grid will contain at least one '1'. The grid is rectangular, width and height do not exceed 100.
- Views
- 3