- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- 2D Dynamic Programming
Dynamic Programming
2D Dynamic Programming
You need a second dimension when the answer depends on two independent positions - how far through each of two strings, or a row and a column in a grid.
Unique paths - the simplest 2D table
Counting routes through a grid
javascript
function uniquePaths(rows, cols) {
const table = Array.from({ length: rows }, () => new Array(cols).fill(1))
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
// Arrive from above or from the left.
table[r][c] = table[r - 1][c] + table[r][c - 1]
}
}
return table[rows - 1][cols - 1]
}
console.log(uniquePaths(3, 7)) // 28