Algorithms · Visualized
Matrix: Max Area of Island (BFS)
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
Similar to Number of Islands, but instead of just counting islands, this finds the size (cell count) of the largest one. Time: O(rows × cols) average, O(rows × cols) worst; space: O(rows × cols) — BFS queue in the worst case.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Max Area of Island (BFS)
Matrix / 2D ArraySimilar to Number of Islands, but instead of just counting islands, this finds the size (cell count) of the largest one. A BFS (breadth-first search) starting from each unvisited land cell explores the whole island level by level, counting cells as it goes.
How Max Area of Island (BFS) Works
- Loop through every cell in the grid, looking for unvisited land cells.
- When one is found, start a BFS: initialize a queue with that cell, mark it visited, and set an area counter to 0.
- While the queue isn't empty, dequeue a cell, increment the area counter by 1, and check its four neighbors.
- For each neighbor that is land and hasn't been visited yet, mark it visited and add it to the queue.
- Once the queue empties, the area counter holds the size of that island — compare it to the largest area found so far, then continue scanning the rest of the grid for other unvisited islands.
Max Area of Island (BFS) Worked Example
Input: [[0, 0, 1, 0], [0, 1, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]
BFS from (0,2): explores (0,2),(1,2),(1,1),(2,1) — connected island of size 4. Continue scanning: finds isolated land at (3,0) — BFS gives island of size 1. Largest area found: 4.
from collections import deque
def max_area_island(grid):
best = 0
rows, cols = len(grid), len(grid[0])
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
area = 0
q = deque([(r, c)])
grid[r][c] = 0
while q:
cr, cc = q.popleft()
area += 1
for nr, nc in [(cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)]:
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 0
q.append((nr, nc))
best = max(best, area)
return bestBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Max Area of Island (BFS) Time & Space Complexity
When to Use Max Area of Island (BFS)
- Finding the largest connected region in image segmentation or geographic data.
- Resource cluster analysis — e.g. finding the largest connected group of available servers/nodes in a grid layout.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.