Problem 463

Abstract / Summary

Count the edges of land cells that border water or the grid edge to find the island perimeter.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0463.py

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        width  = len(grid[0])
        height = len(grid)

        result = 0
        for y in range(height):
            for x in range(width):
                if grid[y][x] == 1: # land
                    if x == 0 or grid[y][x-1] == 0:
                        result += 1
                    if y == 0 or grid[y-1][x] == 0:
                        result += 1
                    if x == width-1  or grid[y][x+1] == 0:
                        result += 1
                    if y == height-1 or grid[y+1][x] == 0:
                        result += 1

        return result
19 lines | 672 bytes | submitted September 7, 2023 | GitHub   5% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Depth First Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the perimeter of a single island represented in a two-dimensional binary grid. Each cell contains either 1 (land) or 0 (water). The algorithm walks the grid once, examines every land cell, and adds to a running total the number of its sides that border water or the outer boundary of the grid. The final total is the island’s perimeter.

Key Steps

Determining Grid Dimensions

The first two statements capture the horizontal and vertical extents of the input matrix.

width  = len(grid[0])
height = len(grid)

These values are used throughout the loops to avoid repeated length calculations.

Iterating Over All Cells

Two nested loops enumerate every coordinate (x, y) in row-major order.

for y in range(height):
    for x in range(width):
        if grid[y][x] == 1:  # land
            # perimeter contribution logic follows

The conditional grid[y][x] == 1 isolates land cells, ensuring that water cells are ignored entirely.

Adding Contributions From Each Side

For a land cell, the algorithm checks each of the four cardinal directions. If the neighboring cell is water or the current cell lies on the grid edge, one unit is added to the perimeter count.

if x == 0 or grid[y][x-1] == 0:
    result += 1
if y == 0 or grid[y-1][x] == 0:
    result += 1
if x == width-1 or grid[y][x+1] == 0:
    result += 1
if y == height-1 or grid[y+1][x] == 0:
    result += 1

Each if statement corresponds to the left, top, right, and bottom sides respectively. The use of short-circuit logical operators guarantees that boundary checks are performed before indexing into the grid, preventing out-of-range accesses.

Returning the Accumulated Result

After all cells have been processed, the accumulated result holds the total perimeter and is returned.

return result

Edge Cases Handled

When a land cell touches the outer border of the grid, the corresponding side is automatically counted because the condition x == 0, y == 0, x == width-1, or y == height-1 evaluates to true. This correctly treats the grid edge as water, contributing to the perimeter.

A single isolated land cell (a 1×1 island) is fully surrounded by water or the grid boundary, so each of the four side checks adds one, yielding a perimeter of 4.

If the island occupies an entire row or column, the algorithm still counts the outer sides while ignoring interior adjacencies, because interior neighbors are land (grid[...] == 1) and therefore do not trigger a perimeter increment.

Complex shapes with holes are not possible under the problem’s constraints (the island is guaranteed to be one connected component without lakes), but the logic would still correctly count perimeter contributions for any configuration of land and water cells.

Performance Optimizations

The solution performs a single pass over the grid, visiting each cell exactly once. By checking only the four immediate neighbors of a land cell, it avoids any redundant scanning or auxiliary data structures. The perimeter is accumulated in a scalar variable, keeping auxiliary memory usage constant regardless of grid size.

Boundary checks are integrated directly into the neighbor tests, eliminating the need for separate preprocessing steps or sentinel padding around the grid. This in-place handling reduces both runtime overhead and memory footprint.

Overall, the algorithm achieves the minimal amount of work required to compute the perimeter: one iteration over all cells with a constant amount of work per land cell.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid like a sheet of graph paper that has some water squares and some island squares. The island squares are painted with the number one. This code goes through every single square on the paper one by one. When the computer finds a square that is part of the island, it looks at the neighbors on the left, right, top, and bottom. Each time a neighbor is either the edge of the paper or a square full of water, that means a piece of the island is touching the water. Each touch counts as one side of the island fence. The code adds up all those sides to find the length of the perimeter around the island.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.15 | σ = 0.93

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim Python
everthis JS
fartem Ruby
fpdjsns C++
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim Python
everthis JavaScript
fartem Ruby
fpdjsns C++
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
zfang399 C++
40 links | 27 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

29 easy 13 medium
43 solutions   September 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality