Unique Paths in TypeScript

function uniquePaths(m: number, n: number): number {
    // Initialize a 2D array with dimensions m x n filled with 0s
    let dp: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));

    // Fill the first row and the first column with 1s
    // Since there's only one way to reach any cell in the first row or column
    for (let i = 0; i < m; i++) dp[i][0] = 1;
    for (let j = 0; j < n; j++) dp[0][j] = 1;

    // Iterate through the grid starting from dp[1][1]
    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            // The number of ways to reach the current cell is the sum of the ways
            // to reach the cell directly above and the cell to the left
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        }
    }

    // Return the number of unique paths to reach the bottom-right corner
    return dp[m - 1][n - 1];
}

PrevNext