Created
November 3, 2017 10:35
-
-
Save levymoreira/97417e1a2eaf2ea5d13411463438a5c5 to your computer and use it in GitHub Desktop.
Matrix memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Matrix { | |
constructor() { | |
this.matrix = [ | |
[false, false, false, false], | |
[false, true, false, false], | |
[false, true, false, false], | |
[false, false, false, false] | |
]; | |
} | |
isValidPath(row, col) { | |
return this.matrix[row] === undefined || | |
this.matrix[row][col] === undefined || | |
this.matrix[row][col] === true; | |
} | |
isEnd(row, col) { | |
return row === this.matrix.length - 1 && col === this.matrix[0].length - 1; | |
} | |
/** | |
* Find the number of paths to the end of the matrix. | |
* Normally: Time O(2^n^2) | |
* With memoization: Time O(n^2) | |
*/ | |
countPaths(row, col, cache = []) { | |
if (this.isValidPath(row, col)) { | |
return 0; | |
} | |
if (this.isEnd(row, col)) { | |
return 1; | |
} | |
if (!cache[row] || !cache[row][col]) { | |
if (!cache[row]) { | |
cache[row] = []; | |
} | |
cache[row][col] = this.countPaths(row + 1, col) + this.countPaths(row, col + 1); | |
} | |
return cache[row][col]; | |
} | |
} | |
const test = (currentResult, expectedResult) => { | |
if (currentResult !== expectedResult) { | |
console.log('Error!'); | |
} else { | |
console.log('Success.'); | |
} | |
} | |
var obj = new Matrix(); | |
console.log(test(obj.countPaths(0, 0), 5)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment