Problem Statement:
Given a grid of size m x n, you need to find the number of unique paths from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time.
The calc function recursively computes the number of unique paths from a given cell (i, j) in the grid to the bottom-right corner (m-1, n-1).
Base Case (Reaching the Bottom-Right Corner):
(i, j) is the bottom-right corner (m-1, n-1), return 1 because there's exactly one unique path (the path where you are already at the destination).Out of Bounds Case:
(i, j) is outside the grid boundaries (i.e., i >= m or j >= n), return 0 since there are no valid paths from this point.Memoization Check:
(i, j) has already been computed and stored in dp[i][j]. If dp[i][j] is not -1, return the cached value to avoid redundant calculations and improve efficiency.Recursive Calculation:
calc for the right and down cells:
calc(i, j+1) (move right)calc(i+1, j) (move down)(i, j).dp[i][j] for future use.The uniquePaths function initializes the memoization array and starts the recursive calculation from the top-left corner (0, 0).
Initialization of DP Array:
dp of size (m+1) x (n+1) initialized with -1. This 2D array will store the number of unique paths from each cell. The extra row and column are included to handle boundary conditions more gracefully.Initial Call to calc:
(0, 0) by calling the calc function.Special Case for 1x1 Grid:
1x1, return the result directly (which is 1, as there is only one cell).Return the Result:
dp[0][0], which represents the top-left cell.Input:
m = 3, n = 2
Output:
3
Explanation:
There are 3 unique paths from the top-left to the bottom-right corner in a 3x2 grid:
Input:
m = 1, n = 5
Output:
1
Explanation:
In a 1x5 grid, there is only one path: move right repeatedly.
Input:
m = 6, n = 1
Output:
1
Explanation:
In a 6x1 grid, there is only one path: move down repeatedly.
Input:
m = 4, n = 4
Output:
20
Explanation:
There are 20 unique paths from the top-left to the bottom-right corner in a 4x4 grid.
Input:
m = 10, n = 10
Output:
48620
Explanation:
The number of unique paths for a 10x10 grid is 48620.
O(m * n), where m and n are the number of rows and columns in the grid.O(m * n) for storing the memoization array.Loading component...
Loading component...