02. Unique Paths in a Grid
β GFG solution to the Unique Paths in a Grid problem: count ways to traverse a grid with obstacles using optimized DP.
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a 2D list grid[][]
of size n Γ m
consisting of values 0
and 1
.
A value of
0
means that you can enter that cell.A value of
1
implies that entry to that cell is not allowed (an obstacle).
You start at the upper-left corner of the grid (1, 1)
and you have to reach the bottom-right corner (n, m)
by moving only right or down at each step. Your task is to calculate the total number of ways to reach the target.
Note: The first (1, 1)
and last (n, m)
cells of the grid can also be 1
. It is guaranteed that the total number of ways will fit within a 32-bit integer.
π Examples
Example 1
Input: n = 3, m = 3,
grid = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]
Output: 2
Explanation:
There are two ways to reach the bottom-right corner:
1. Right β Right β Down β Down
2. Down β Down β Right β Right
Example 2
Input: n = 1, m = 3,
grid = [[1, 0, 1]]
Output: 0
Explanation:
The start cell (1,1) is blocked by an obstacle (value = 1), so no path exists.
π Constraints
$1 \le n \times m \le 10^6$
Each
grid[i][j]
is either0
or1
.The result will fit in a 32-bit integer.
β
My Approach
We use dynamic programming with a 1D rolling array to count the number of ways to reach each cell, optimizing space.
π‘ Idea:
Let
dp[j]
represent the number of ways to reach cell(i, j)
in the current rowi
.We iterate row by row. For each cell:
If
grid[i][j] == 1
(obstacle), setdp[j] = 0
(no way).Else, if
j > 0
, adddp[j - 1]
(ways from the left) todp[j]
(which already holds ways from above).
Initialize
dp[0]
as1
ifgrid[0][0] == 0
, else0
.
This effectively uses the previous rowβs dp[j]
values (ways from above) and the current rowβs left neighbor dp[j - 1]
(ways from left).
βοΈ Algorithm Steps:
Let
r = n
,c = m
. Create a 1D arraydp
of sizec
, initialized to all zeros.If
grid[0][0] == 0
, setdp[0] = 1
; otherwisedp[0] = 0
.For each row
i
from0
tor - 1
:For each column
j
from0
toc - 1
:If
grid[i][j] == 1
:dp[j] = 0
(no paths through an obstacle).
Else if
j > 0
:dp[j] += dp[j - 1]
(add ways from the left).
At the end,
dp[c - 1]
holds the number of ways to reach(r - 1, c - 1)
.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ m), as we process each of the $n \times m$ cells exactly once.
Expected Auxiliary Space Complexity: O(m), since we use a single array of size
m
for DP.
π§βπ» Code (C++)
class Solution {
public:
int uniquePaths(vector<vector<int>> &grid) {
int r = grid.size(), c = grid[0].size();
vector<int> dp(c);
dp[0] = grid[0][0] == 0;
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
if (grid[i][j]) dp[j] = 0;
else if (j) dp[j] += dp[j - 1];
return dp[c - 1];
}
};
π§βπ» Code (Java)
class Solution {
public int uniquePaths(int[][] grid) {
int r = grid.length, c = grid[0].length;
int[] dp = new int[c];
dp[0] = grid[0][0] == 0 ? 1 : 0;
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
if (grid[i][j] == 1) dp[j] = 0;
else if (j > 0) dp[j] += dp[j - 1];
return dp[c - 1];
}
}
π Code (Python)
class Solution:
def uniquePaths(self, grid):
r, c = len(grid), len(grid[0])
dp = [0] * c
dp[0] = 1 if grid[0][0] == 0 else 0
for i in range(r):
for j in range(c):
if grid[i][j] == 1:
dp[j] = 0
elif j > 0:
dp[j] += dp[j - 1]
return dp[-1]
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated