class Solution {
private rows: number;
private cols: number;
numIslands(grid: string[][]): number {
if (grid.length === 0) return 0;
this.rows = grid.length;
this.cols = grid[0].length;
let count = 0;
for (let r = 0; r < this.rows; r++) {
for (let c = 0; c < this.cols; c++) {
if (grid[r][c] === '1') {
count++;
this.dfs(grid, r, c);
}
}
}
return count;
}
private dfs(grid: string[][], r: number, c: number): void {
if (r < 0 || c < 0 || r >= this.rows || c >= this.cols || grid[r][c] === '0') {
return;
}
grid[r][c] = '0'; // mark visited
this.dfs(grid, r - 1, c); // up
this.dfs(grid, r + 1, c); // down
this.dfs(grid, r, c - 1); // left
this.dfs(grid, r, c + 1); // right
}
}
// Driver code
const grid = [
['1','1','0','0','0'],
['1','1','0','0','1'],
['0','0','0','1','1'],
['0','0','0','0','0'],
['1','0','1','0','1']
];
const solution = new Solution();
const result = solution.numIslands(grid);
console.log(result);if (grid[r][c] === '1') {
Check if current cell is land to start island count and DFS
Increment island count for new island found
Start DFS to mark all connected land cells as visited
if (r < 0 || c < 0 || r >= this.rows || c >= this.cols || grid[r][c] === '0') { return; }
Stop DFS if out of bounds or water/visited cell
Mark current land cell as visited to avoid revisiting
this.dfs(grid, r - 1, c); this.dfs(grid, r + 1, c); this.dfs(grid, r, c - 1); this.dfs(grid, r, c + 1);
Recursively visit all four neighbors to cover entire island