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...
Main Function is not defined.
INPUT: m = 3 , n = 7
OUTPUT: 28
public static int uniquePaths( int m , int n){
vector<vector<int>> dp(m+1 , vector<int>(n+1 , -1));
int i(0) , j(0);
int num = calc(i , j , m , n, dp);
if(m == 1 && n ==1){
return num;
}
return dp[0][0];
}//function end
public static int calc(int i , int j , int m , int n, vector<vector<int>> &dp){
if( i == m-1 and j == n-1){
return 1;
}
if(i == m || j == n){
return 0;
}
if( dp[i][j] != -1){
return dp[i][j];
}
int a1 = calc(i+1 , j , m , n, dp);
int a2 = calc(i , j+1, m,n,dp);
return a1 + a2;
}//function end