Skip to content

Instantly share code, notes, and snippets.

@bluesockets
Created March 12, 2021 18:10
Show Gist options
  • Save bluesockets/f3cca5e3dc584b564fbea87c4f33dd88 to your computer and use it in GitHub Desktop.
Save bluesockets/f3cca5e3dc584b564fbea87c4f33dd88 to your computer and use it in GitHub Desktop.
function numberOfPaths (matrix) {
// Write your code here
if (matrix.length < 1) return 0
// if matrix[matrix.length-1] === 0 and matrix[matrix.length -1] == 0 then return 0
// set up 2d cache to cumulate the possible moves
const cache = Array.from(Array(matrix.length + 1), () => new Array(matrix[0].length + 1).fill(null))
// set up initial values
cache[1][1] = 1
// tabulate the total number of moves it will take to get to the y * x square
// logic is that if we land on tile where a top or left neighbor is 0 then that path is dead
for (let i = 1; i < cache.length; i++) {
for (let j = 1; j < cache[i].length; j++) {
if (cache[i][j] === null) {
const matrixSquare = matrix[i - 1][j - 1]
const top = matrixSquare === 1 ? cache[i - 1][j] : 0
const left = matrixSquare === 1 ? cache[i][j - 1] : 0
let tile = 0
if (top === 1) tile++
if (left === 1) tile++
cache[i][j] = tile
}
}
}
console.log(JSON.stringify(cache, null, 1))
return cache[matrix.length][matrix[0].length]
}
const input = [[1, 1, 0], [0, 1, 1], [1, 1, 1]]
const paths = numberOfPaths(input)
console.log(`paths: ${paths}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment