463. Island Perimeter #152
-
Topics: You are given Grid cells are connected horizontally/vertically (not diagonally). The The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can iterate through each cell in the grid and apply the following logic:
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 = count($grid[0]);
$perimeter = 0;
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
if ($grid[$i][$j] == 1) {
// Add 4 for the current land cell
$perimeter += 4;
// Check if the cell has a right neighbor that's also land
if ($j < $cols - 1 && $grid[$i][$j + 1] == 1) {
$perimeter -= 2; // Subtract 2 for the shared edge with the right neighbor
}
// Check if the cell has a bottom neighbor that's also land
if ($i < $rows - 1 && $grid[$i + 1][$j] == 1) {
$perimeter -= 2; // Subtract 2 for the shared edge with the bottom neighbor
}
}
}
}
return $perimeter;
}
// Example usage:
$grid = [
[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]
];
echo islandPerimeter($grid); // Output: 16
?> Explanation:
Example Output:For the provided grid: $grid = [
[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]
];
echo islandPerimeter($grid); // Output: 16 The output will be |
Beta Was this translation helpful? Give feedback.
We can iterate through each cell in the grid and apply the following logic:
grid[i][j] = 1
), assume it contributes4
to the perimeter (each side of the cell).grid[i][j + 1] = 1
) or below it (grid[i + 1][j] = 1
), the perimeter is reduced by2
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