#13
Graph BFS/DFS (grid)
Graph DFSGiven a grid of '1' (land) and '0' (water), count the islands (groups of land connected horizontally/vertically).
function numIslands(grid: string[][]): number {
const rows = grid.length, cols = grid[0]?.length ?? 0;
let count = 0;
const sink = (r: number, c: number): void => {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] !== '1') return;
grid[r][c] = '0'; // mark visited in place
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
};
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++)
if (grid[r][c] === '1') { count++; sink(r, c); }
return count;
}def num_islands(grid)
rows = grid.length
cols = rows.zero? ? 0 : grid[0].length
count = 0
sink = lambda do |r, c|
return if r.negative? || c.negative? || r >= rows || c >= cols || grid[r][c] != '1'
grid[r][c] = '0' # mark visited in place
sink.call(r + 1, c)
sink.call(r - 1, c)
sink.call(r, c + 1)
sink.call(r, c - 1)
end
rows.times do |r|
cols.times do |c|
next unless grid[r][c] == '1'
count += 1
sink.call(r, c)
end
end
count
end