1. Stop conditions
Return on out-of-bounds cells or water.
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === "0") {Typorithm · medium
Step 1 of 8 · intro card
Graphs
Scan the grid; each unvisited land cell starts an island, and a DFS flood-fill sinks its whole connected body.
An island is a maximal group of orthogonally connected land cells.
Scanning the grid, every '1' not yet sunk begins a new island and triggers a flood fill.
The flood fill marks each reached land cell as water so it is never counted twice.
Each fresh land cell = +1 island.
Flood fill sinks the whole island.
Mark visited to prevent recounting.
function numIslands(grid) {
const rows = grid.length;
const cols = grid[0].length;
let count = 0;
function sink(r, c) {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === "0") {
return;
}
grid[r][c] = "0";
sink(r + 1, c);
sink(r - 1, c);
sink(r, c + 1);
sink(r, c - 1);
}
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (grid[r][c] === "1") {
count += 1;
sink(r, c);
}
}
}
return count;
}Connect each part of the code to the concept before you type.
Return on out-of-bounds cells or water.
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === "0") {Mark visited land as water to avoid recounting.
grid[r][c] = "0"Recurse into all four orthogonal directions.
sink(r + 1, c)Each unvisited land cell starts a fresh island.
count += 1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.