LeetCode: Where Will the Ball Fall Solution

If I remember correctly, Alex K. also loves recursion

Approach

Keep in mind for the cases of:

  • borders
  • V shape

Implementation

1var findBall = function (grid) {
2 const [m, n] = [grid.length, grid[0].length]
3
4 const recursion = (i, j) => {
5 if (i === m) return j
6
7 // the borders
8 if (j === 0 && grid[i][j] === -1) return -1
9 if (j === n - 1 && grid[i][j] === 1) return -1
10
11 // the \/s
12 if (grid[i][j] === 1 && grid[i][j + 1] === -1) return -1
13 if (grid[i][j] === -1 && grid[i][j - 1] === 1) return -1
14
15 return recursion(i + 1, j + grid[i][j])
16 }
17
18 return Array.from({ length: n }, (_, j) => recursion(0, j))
19}

References

Original problem

Comments

Loading comments...

Tags

leetcode

array

matrix

recursion

dfs

Next Post

LeetCode: Multiply Strings

Aug 28, 2022

Will make this better. Word promised!

Previous Post

LeetCode: Spiral Matrix

Aug 25, 2022

Writing recursive function is fun

HoningJS

Search Posts