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
0means that you can enter that cell.A value of
1implies 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 → RightExample 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 either0or1.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]as1ifgrid[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 arraydpof sizec, initialized to all zeros.If
grid[0][0] == 0, setdp[0] = 1; otherwisedp[0] = 0.For each row
ifrom0tor - 1:For each column
jfrom0toc - 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
mfor 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