Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'.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:
Imagine looking at a vast map filled with land and water, and your goal is to count every separate patch of land. The brute force approach involves inspecting every single location on the map, and whenever you find a piece of land, you exhaustively explore every possible path connected to it to map out its entire shape.
Here's how the algorithm would work step-by-step:
def numIslands(grid):
if not grid:
return 0
row_count = len(grid)
col_count = len(grid[0])
island_counter = 0
# Scan the entire map to find unvisited land starting points for new islands
for current_row in range(row_count):
for current_col in range(col_count):
if grid[current_row][current_col] == "1":
island_counter += 1
# Exhaustively explore and sink all connected land to prevent duplicate counting
stack = [(current_row, current_col)]
while stack:
row_pos, col_pos = stack.pop()
if 0 <= row_pos < row_count and 0 <= col_pos < col_count and grid[row_pos][col_pos] == "1":
grid[row_pos][col_pos] = "0"
stack.append((row_pos + 1, col_pos))
stack.append((row_pos - 1, col_pos))
stack.append((row_pos, col_pos + 1))
stack.append((row_pos, col_pos - 1))
return island_counterImagine scanning a vast map of land and water from above to count every separate landmass. The best way to solve this is to systematically search the map, and whenever you spot a piece of land, you instantly explore and mark its entire connected region so you never count it twice.
Here's how the algorithm would work step-by-step:
class Solution:
def numIslands(self, grid: list[list[str]]) -> int:
if not grid:
return 0
row_count = len(grid)
col_count = len(grid[0])
island_counter = 0
# We iterate through every cell to ensure no isolated landmass is ever missed.
for current_row in range(row_count):
for current_col in range(col_count):
if grid[current_row][current_col] == '1':
island_counter += 1
queue_for_bfs = [(current_row, current_col)]
grid[current_row][current_col] = '0'
# We expand outward to consume all connected land so it forms a single counted island.
while queue_for_bfs:
active_row, active_col = queue_for_bfs.pop(0)
row_offsets = [-1, 1, 0, 0]
col_offsets = [0, 0, -1, 1]
for direction_index in range(4):
neighbor_row = active_row + row_offsets[direction_index]
neighbor_col = active_col + col_offsets[direction_index]
# We validate boundaries to prevent out-of-range errors during spread.
if 0 <= neighbor_row < row_count and 0 <= neighbor_col < col_count:
if grid[neighbor_row][neighbor_col] == '1':
grid[neighbor_row][neighbor_col] = '0'
queue_for_bfs.append((neighbor_row, neighbor_col))
return island_counter| Case | How to Handle |
|---|---|
| Empty grid or null input | Check for null or empty grid at the start and return zero immediately. |
| Grid with dimensions 1x1 containing either '0' or '1' | The traversal loop correctly processes the single cell and increments the count if it equals '1'. |
| Grid consisting entirely of '0's with no land | The algorithm scans the entire grid without triggering any DFS or BFS expansions, returning a count of zero. |
| Grid consisting entirely of '1's forming one massive island | The first '1' encountered triggers a full traversal of every cell in the grid, marking all as visited and returning a count of one. |
| Extremely large grid exceeding standard recursion depth limits | Using an iterative Breadth-First Search or explicit stack Depth-First Search prevents stack overflow errors on massive inputs. |
| Snake-like or highly winding island shapes | Graph traversal correctly visits all orthogonally connected neighbors regardless of the tortuous path of the land cells. |
| Ragged or non-rectangular grid dimensions | Assuming a rectangular grid matrix, boundary checks ensure out-of-bounds errors are avoided when inspecting neighbors. |
| Mutating the input grid versus using a separate visited matrix | The solution sinks visited land cells by mutating '1' to '0', avoiding extra space allocation for a visited set. |