The task
is taken from leetcode
Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count 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:
11110 11010 11000 00000
Output: 1
Example 2:
Input:
11000 11000 00100 00011
Output: 3
My solution
/** * @param {character[][]} grid * @return {number} */ function numIslands(grid) { if (grid === null || grid === void 0 || !grid.length || !grid[0].length) { return 0; } const NR = grid.length; const NC = grid[0].length; const check = (grid, pos) => { const {r, c} = pos; if (r < 0 || c < 0 || r >= NR || c >= NC || grid[r][c] === "0" ) { return; } grid[r][c] = "0"; check(grid, {r: r + 1, c}); check(grid, {r: r - 1, c}); check(grid, {r, c: c + 1}); check(grid, {r, c: c - 1}); } let numOfIslands = 0; for (let r = 0; r < NR; r++) { for (let c = 0; c < NC; c++) { if (grid[r][c] === "1") { numOfIslands++; check(grid, {r,c}); } } } return numOfIslands; };