# LeetCode: Number of Islands Solution

*To be consistent, first find out how to make it easy*

## Approach

After detecting a piece of an island (cell with value

1

), recursively spread through all vertical and horizontal directions to discover a full islandCould use any ways to mark the visited state

## Implementation

1var numIslands = function (grid) {2 const [m, n] = [grid.length, grid[0].length]34 let res = 056 const isValidCell = (i, j) => 0 <= i && i < m && 0 <= j && j < n78 const recursion = (i, j) => {9 if (isValidCell(i, j) && grid[i][j] === "1") {10 grid[i][j] = 011 recursion(i + 1, j)12 recursion(i, j + 1)13 recursion(i - 1, j)14 recursion(i, j - 1)15 return16 }17 }1819 for (let i = 0; i < m; i++) {20 for (let j = 0; j < n; j++) {21 if (grid[i][j] === "1") {22 recursion(i, j)23 res++24 }25 }26 }2728 return res29}

## References

## Comments

Loading comments...

## Tags

leetcode

array

matrix

dfs

recursion

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.

## Next Post

## Previous Post

LeetCode: Validate Binary Search Tree

Aug 20, 2022

Traverse in-order and validate the traversed result