You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
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:
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image above.
Example 2:
Input: grid = [[1]] Output: 4
Example 3:
Input: grid = [[1,0]] Output: 4
Constraints:
row == grid.lengthcol == grid[i].length1 <= row, col <= 100grid[i][j] is 0 or 1.grid.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the total perimeter of an island on a grid, the brute force approach inspects every single square one by one. For each land square we find, we thoroughly check its immediate neighbors in all four directions to count how many edges are exposed to the water or the edge of the board.
Here's how the algorithm would work step-by-step:
def islandPerimeter(grid): total_perimeter = 0 row_count = len(grid) column_count = len(grid[0]) # Iterate through every cell in the grid to locate all individual land squares for row_index in range(row_count): for col_index in range(column_count): if grid[row_index][col_index] == 1: directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] for row_offset, col_offset in directions: neighbor_row = row_index + row_offset neighbor_col = col_index + col_offset # Check if neighbor is out of bounds because grid edges count as perimeter if neighbor_row < 0 or neighbor_row >= row_count or neighbor_col < 0 or neighbor_col >= column_count: total_perimeter += 1 # Check if neighbor is water because land borders with water contribute to perimeter elif grid[neighbor_row][neighbor_col] == 0: total_perimeter += 1 # Return the accumulated perimeter count after checking all land squares and their neighbors return total_perimeterInstead of measuring the entire grid all at once, the optimal approach simply inspects every single piece of land one by one. By checking its immediate neighbors, you can instantly determine how many outer edges that specific piece contributes to the final boundary.
Here's how the algorithm would work step-by-step:
class Solution:
def islandPerimeter(self, grid: list[list[int]]) -> int:
total_perimeter = 0
row_count = len(grid)
column_count = len(grid[0])
# We iterate through every cell to evaluate land blocks individually.
for current_row in range(row_count):
for current_col in range(column_count):
if grid[current_row][current_col] == 1:
# Each land block starts with four potential perimeter edges.
for row_offset, col_offset in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
neighbor_row = current_row + row_offset
neighbor_col = current_col + col_offset
# Out-of-bounds or water means this side is exposed to the outer edge.
if neighbor_row < 0 or neighbor_row >= row_count or neighbor_col < 0 or neighbor_col >= column_count:
total_perimeter += 1
elif grid[neighbor_row][neighbor_col] == 0:
total_perimeter += 1
# Return the accumulated outer boundary count after checking all land pieces.
return total_perimeter| Case | How to Handle |
|---|---|
| Null or empty 2D grid input | Check for null or zero-length grids at the beginning and return a perimeter of zero immediately. |
| Minimum sized grid containing a single land cell | Iterate through the single cell and add 4 to the perimeter since all four of its sides are exposed to water or grid boundaries. |
| Grid where all cells are water | Traverse the grid without finding any land cells, resulting in a final returned perimeter of zero. |
| Grid completely filled with land | Each interior cell contributes zero to the perimeter, while boundary cells correctly account for the outer edges. |
| Maximum sized grid constraints | Use an efficient O(rows times cols) single pass traversal to inspect each cell and its neighbors without exceeding time limits. |
| Island with complex shapes like hollow inner lakes or narrow corridors | Checking adjacent cells for water or boundaries naturally accounts for interior perimeter contributions as well. |
| Memory constraints with large grid inputs | Iterate directly through the provided grid in place without allocating additional major data structures, keeping space complexity at O(1). |