Created
December 22, 2019 21:24
-
-
Save syphh/9c6127dcfb0bee0c36945c13e2cb6889 to your computer and use it in GitHub Desktop.
Sum of sub-matrices (dynamic programming method)
This file contains hidden or 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
| function dynamicSumSubmatrices(mat){ | |
| // n and m represent dimensions of the matrix | |
| let n = mat.length; | |
| let m = mat[0].length; | |
| // declaring a (n*m) matrix | |
| let sumMat = [...new Array(n)].map(row => [...new Array(m)]); | |
| // part 1 | |
| sumMat[0][0] = mat[0][0]; | |
| // part 2 | |
| for(let i = 1; i < m; i++) sumMat[0][i] = mat[0][i] + sumMat[0][i-1]; | |
| // part 3 | |
| for(let i = 1; i < n; i++) sumMat[i][0] = mat[i][0] + sumMat[i-1][0]; | |
| // part 4 | |
| for(let i = 1; i < n; i++){ | |
| for(let j = 1; j < m; j++) | |
| sumMat[i][j] = mat[i][j] + sumMat[i-1][j] + sumMat[i][j-1] - sumMat[i-1][j-1]; | |
| } | |
| return sumMat; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment