Skip to content

463. Island Perimeter #152

Answered by topugit
mah-shamim asked this question in Q&A
Jul 30, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We can iterate through each cell in the grid and apply the following logic:

  1. Count Land Cells: For each land cell (grid[i][j] = 1), assume it contributes 4 to the perimeter (each side of the cell).
  2. Subtract Shared Edges: If a land cell has a neighboring land cell either to its right (grid[i][j + 1] = 1) or below it (grid[i + 1][j] = 1), the perimeter is reduced by 2 for each shared edge, since two adjacent cells share a side.

The overall perimeter can be computed by summing up the individual contributions from each land cell, adjusted for shared edges.

Let's implement this solution in PHP: 463. Island Perimeter

<?php
function islandPerimeter($grid) {
    $rows = count($grid);
    $cols = c…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Sep 1, 2024
Maintainer Author

@topugit
Comment options

topugit Sep 1, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants