πΊοΈ Grid DP: Finding Your Way Through a Maze
The Story of the Maze Runner
Imagine youβre a tiny robot π€ standing at the top-left corner of a grid. Your mission? Reach the treasure chest at the bottom-right corner!
But hereβs the twist: you can only move RIGHT or DOWN. No going back, no going up. Just like a one-way street!
This is Grid Dynamic Programming β and once you understand it, youβll feel like a path-finding wizard! π§ββοΈ
π― What is DP on Grids?
Think of a grid like a chocolate bar π« with squares. Each square is a βcellβ you can visit.
The Big Idea:
To know the best way to reach ANY cell, just look at the cells that could have led to it (the one above and the one to the left).
graph TD A["Start π"] --> B["Move Right β"] A --> C["Move Down β"] B --> D["Keep Going..."] C --> D D --> E["Reach Goal π―"]
Why is this powerful?
- Instead of trying every possible path (which takes forever! β°)
- We build our answer step by step
- Each cell remembers its answer so we donβt repeat work
π€οΈ Unique Paths: How Many Roads Lead to Treasure?
The Problem
You have a grid with m rows and n columns. Starting from top-left, how many different ways can you reach bottom-right?
Real-Life Analogy ποΈ
Imagine walking in a city with streets forming a grid. You can only walk East or South. How many different routes exist to reach the park?
START βββββββββ
β β
β β β
β β
ββββββββ PARK
The Magic Formula β¨
For any cell (i, j):
paths[i][j] = paths[i-1][j] + paths[i][j-1]
β β
from above from left
Translation: The ways to reach a cell = ways from above + ways from left!
Step-by-Step Example
Letβs find paths in a 3Γ3 grid:
βββββ¬ββββ¬ββββ
β 1 β 1 β 1 β β Only one way along top edge
βββββΌββββΌββββ€
β 1 β 2 β 3 β β 2 = 1+1, 3 = 1+2
βββββΌββββΌββββ€
β 1 β 3 β 6 β β Answer: 6 paths! π
βββββ΄ββββ΄ββββ
The Code π»
function uniquePaths(m, n) {
// Create grid filled with 1s
const dp = Array(m).fill(null)
.map(() => Array(n).fill(1));
// Fill in the magic numbers
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
// Example: 3x3 grid
console.log(uniquePaths(3, 3)); // Output: 6
Why First Row & Column are All 1s? π€
- First row: Only one way β keep going RIGHT βββ
- First column: Only one way β keep going DOWN βββ
No choices means exactly 1 path!
π° Minimum Path Sum: Cheapest Route to the Treasure
The Problem
Now each cell has a cost (think of it as coins you must pay). Find the path with the lowest total cost.
Real-Life Analogy π
Youβre driving through toll booths. Each road segment has a toll fee. Find the cheapest route from home to work!
βββββββ¬ββββββ¬ββββββ
β $1 β $3 β $1 β
βββββββΌββββββΌββββββ€
β $1 β $5 β $1 β
βββββββΌββββββΌββββββ€
β $4 β $2 β $1 β
βββββββ΄ββββββ΄ββββββ
The Magic Formula β¨
For any cell (i, j):
minCost[i][j] = grid[i][j] + min(
minCost[i-1][j], // cost from above
minCost[i][j-1] // cost from left
)
Translation: Minimum cost = cellβs cost + cheaper of (coming from above OR left)
Step-by-Step Example
Using the grid above:
Original: Minimum Costs:
βββββ¬ββββ¬ββββ βββββ¬ββββ¬ββββ
β 1 β 3 β 1 β β 1 β 4 β 5 β
βββββΌββββΌββββ€ β βββββΌββββΌββββ€
β 1 β 5 β 1 β β 2 β 7 β 6 β
βββββΌββββΌββββ€ βββββΌββββΌββββ€
β 4 β 2 β 1 β β 6 β 8 β 7 β β Answer!
βββββ΄ββββ΄ββββ βββββ΄ββββ΄ββββ
Cheapest path: 1β1β4β2β1 = $7 π
The Code π»
function minPathSum(grid) {
const m = grid.length;
const n = grid[0].length;
// Build first row (can only come from left)
for (let j = 1; j < n; j++) {
grid[0][j] += grid[0][j-1];
}
// Build first column (can only come from above)
for (let i = 1; i < m; i++) {
grid[i][0] += grid[i-1][0];
}
// Fill rest with minimum of top or left
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
grid[i][j] += Math.min(
grid[i-1][j],
grid[i][j-1]
);
}
}
return grid[m-1][n-1];
}
// Example
const grid = [
[1, 3, 1],
[1, 5, 1],
[4, 2, 1]
];
console.log(minPathSum(grid)); // Output: 7
π Key Insights to Remember
Pattern Recognition π§©
| Problem | What We Track | Formula |
|---|---|---|
| Unique Paths | Count of ways | dp[i][j] = dp[i-1][j] + dp[i][j-1] |
| Min Path Sum | Minimum cost | dp[i][j] = cost + min(above, left) |
The Grid DP Recipe π
- Create a DP table (same size as grid)
- Fill base cases (first row & column)
- Fill remaining cells using the formula
- Answer is in bottom-right corner
graph TD A["Create DP Table"] --> B["Fill First Row"] B --> C["Fill First Column"] C --> D["Fill Remaining Cells"] D --> E["Return Bottom-Right Value"]
π Pro Tips
Tip 1: Space Optimization
You donβt always need a full 2D array! For many grid problems, you only need the previous row:
// Space-optimized Unique Paths
function uniquePathsOptimized(m, n) {
const dp = Array(n).fill(1);
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[j] += dp[j-1];
}
}
return dp[n-1];
}
Tip 2: Identify Grid DP Problems
Ask yourself:
- Can I only move in limited directions?
- Does each cell depend on previous cells?
- Am I counting paths or finding optimal value?
If yes β Grid DP! β
π¬ Summary: Your Grid DP Journey
You started as a confused traveler. Now youβre a Grid DP Master! π
What you learned:
- Grid DP breaks big problems into tiny cell-by-cell decisions
- Unique Paths counts ways by adding paths from above and left
- Minimum Path Sum finds cheapest route by choosing the minimum
Remember the mantra:
βTo solve any cell, just look at where I came from!β
Now go forth and conquer those grids! πΊοΈβ¨
