LeetCode: Max Area Of Island Solution

1var maxAreaOfIsland = function (grid) {
2 const [m, n] = [grid.length, grid[0].length]
3 const visited = Array.from({ length: m }, _ => Array(n).fill(false))
4
5 const valid = (row, col) => {
6 return (
7 row >= 0 &&
8 row < m &&
9 col >= 0 &&
10 col < n &&
11 !visited[row][col] &&
12 grid[row][col] !== 0
13 )
14 }
15
16 const traverse = (row, col) => {
17 if (!valid(row, col)) {
18 return 0
19 }
20
21 visited[row][col] = true
22
23 return (
24 1 +
25 traverse(row, col + 1) +
26 traverse(row, col - 1) +
27 traverse(row + 1, col) +
28 traverse(row - 1, col)
29 )
30 }
31
32 let res = 0
33 for (let row = 0; row < m; row++) {
34 for (let col = 0; col < n; col++) {
35 res = Math.max(res, traverse(row, col))
36 }
37 }
38
39 return res
40}

Comments

Loading comments...

Tags

leetcode

array

matrix

dfs

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

CSSBattle 1.4: Ups n Downs

HoningJS

Search Posts