![]() |
VOOZH | about |
Given a 2D grid of 0s (obstacles) and 1s (valid paths), find the number of valid paths from the top-left corner to the bottom-right corner. You can only move down or right.
Examples:
Input: grid = [ [1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output:2Input: grid = [ [1, 1], [1, 1]]
Output:1
Idea is to use a recursive approach to explore all possible paths from the starting cell to the ending cell and check if the unique and valid paths.
(0, 0).(i, j) to (i+1, j) if it's a valid path.(i, j) to (i, j+1) if it's a valid path.(i, j) reaches the bottom-right cell (m-1, n-1), increment the count of valid paths.Below is the implementation of the approach:
1 2
Time Complexity: O(2m+n) where m is the number of rows and n is the number of columns.
Auxiliary Space: O(m+n) for the recursion stack.
Use a 2D
dparray to store the number of valid paths to reach each cell in the grid. The DP approach is significantly more efficient than the naïve recursive approach because it avoids redundant computations by storing the solutions to subproblems in a 2D array.
dp array of the same size as the grid.dp:dp[i][0] = 1 if grid[i][0] == 1, else dp[i][0] = 0dp[0][j] = 1 if grid[0][j] == 1, else dp[0][j] = 0(i, j) in the grid, update dp[i][j] as:dp[i][j] = dp[i-1][j] + dp[i][j-1] if grid[i][j] == 1, else dp[i][j] = 0Below is the implementation of the approach:
1 2
Time Complexity: O(m×n) where m is the number of rows and n is the number of columns.
Auxiliary Space: O(m×n) for the creating dp array