LeetCode: Where Will the Ball Fall Solution
If I remember correctly, Alex K. also loves recursionApproach
Keep in mind for the cases of:
- borders
- V shape
Implementation
1var findBall = function (grid) {2 const [m, n] = [grid.length, grid[0].length]34 const recursion = (i, j) => {5 if (i === m) return j67 // the borders8 if (j === 0 && grid[i][j] === -1) return -19 if (j === n - 1 && grid[i][j] === 1) return -11011 // the \/s12 if (grid[i][j] === 1 && grid[i][j + 1] === -1) return -113 if (grid[i][j] === -1 && grid[i][j - 1] === 1) return -11415 return recursion(i + 1, j + grid[i][j])16 }1718 return Array.from({ length: n }, (_, j) => recursion(0, j))19}
References
Comments
Loading comments...
Tags
leetcode
array
matrix
recursion
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
LeetCode: Multiply Strings
Will make this better. Word promised!
Previous Post
LeetCode: Spiral Matrix
Writing recursive function is fun