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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 695: Max Area of Island
- problem 733: Flood Fill
- problem 1034: Coloring A Border
Solved On The Same Day
- problem 415: Add Strings
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- 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