Grid DP

Back

Loading concept...

๐Ÿ—บ๏ธ Grid DP: Finding Your Way Through a Maze of Numbers

Imagine youโ€™re a tiny explorer standing at the top-left corner of a checkerboard. Your mission? Get to the bottom-right corner. But hereโ€™s the twistโ€”you can only move right or down. Welcome to Grid Dynamic Programming!


๐ŸŽฏ What is Grid DP?

Think of a grid like a big chocolate bar divided into squares. Grid DP is a clever way to solve problems where you need to move through this โ€œchocolate barโ€ from one corner to another.

The Magic Rule: You can only go โ†’ right or โ†“ down. No going back!

graph TD A["Start โ†–"] --> B["Move Right โ†’"] A --> C["Move Down โ†“"] B --> D["Keep Going..."] C --> D D --> E["Reach End โ†˜"]

๐Ÿšถ Unique Paths: How Many Ways Can You Get There?

The Story

Imagine youโ€™re a little robot in a warehouse. You start at the top-left corner and need to reach the bottom-right corner to pick up a package. You can only move right or down.

Question: How many different paths can you take?

The Simple Idea

At each square, you can arrive from:

  • The square above (came down)
  • The square to the left (came right)

So the number of ways to reach any square = ways from above + ways from left!

Visual Example (3ร—3 Grid)

โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”
โ”‚ 1 โ”‚ 1 โ”‚ 1 โ”‚  โ† Top row: only 1 way each
โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค
โ”‚ 1 โ”‚ 2 โ”‚ 3 โ”‚  โ† 2 = 1+1, 3 = 1+2
โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค
โ”‚ 1 โ”‚ 3 โ”‚ 6 โ”‚  โ† 6 paths to reach goal!
โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜

Python Code

def uniquePaths(m, n):
    # Create a grid filled with 1s
    dp = [[1] * n for _ in range(m)]

    # Fill the grid
    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = dp[i-1][j] + dp[i][j-1]

    return dp[m-1][n-1]

# Example: 3x3 grid
print(uniquePaths(3, 3))  # Output: 6

Why Does This Work?

Position Calculation Result
(0,0) Start 1
(1,1) 1 + 1 2
(2,2) 3 + 3 6

First row and column are always 1 because thereโ€™s only one way to reach them (go straight right or straight down).


๐Ÿ’ฐ Minimum Path Sum: The Cheapest Route

The Story

Now imagine each square has coins on it. Some squares have lots of coins (expensive!), some have few (cheap!). You want to find the path that picks up the fewest coins possible.

The Simple Idea

At each square, pick the cheaper way to arrive:

  • Cost from above, OR
  • Cost from the left

Add the current squareโ€™s cost to the cheaper option!

Visual Example

Grid with costs:        Minimum costs to reach:
โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”           โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”
โ”‚ 1 โ”‚ 3 โ”‚ 1 โ”‚           โ”‚ 1 โ”‚ 4 โ”‚ 5 โ”‚
โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค           โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค
โ”‚ 1 โ”‚ 5 โ”‚ 1 โ”‚    โ†’      โ”‚ 2 โ”‚ 7 โ”‚ 6 โ”‚
โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค           โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค
โ”‚ 4 โ”‚ 2 โ”‚ 1 โ”‚           โ”‚ 6 โ”‚ 8 โ”‚ 7 โ”‚
โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜           โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜

Minimum path cost = 7 โœจ
Path: 1โ†’3โ†’1โ†’1โ†’1 or 1โ†’1โ†’5โ†’1โ†’1

Python Code

def minPathSum(grid):
    m, n = len(grid), len(grid[0])

    # Fill first row (can only come from left)
    for j in range(1, n):
        grid[0][j] += grid[0][j-1]

    # Fill first column (can only come from above)
    for i in range(1, m):
        grid[i][0] += grid[i-1][0]

    # Fill rest of grid
    for i in range(1, m):
        for j in range(1, n):
            grid[i][j] += min(
                grid[i-1][j],  # from above
                grid[i][j-1]   # from left
            )

    return grid[m-1][n-1]

# Example
grid = [[1,3,1], [1,5,1], [4,2,1]]
print(minPathSum(grid))  # Output: 7

๐Ÿง  The Grid DP Pattern (Your Secret Formula!)

Every Grid DP problem follows this recipe:

graph TD A["1. Create a DP table"] --> B["2. Handle base cases"] B --> C["3. Fill row by row"] C --> D["4. Use formula at each cell"] D --> E["5. Answer is at bottom-right"]

The Universal Formula

dp[i][j] = combine(dp[i-1][j], dp[i][j-1]) + current_value
Problem Combine Function
Unique Paths + (add both)
Min Path Sum min() (pick smaller)
Max Path Sum max() (pick bigger)

๐ŸŽฎ Think of It Like a Video Game!

Unique Paths = โ€œHow many different ways can I complete this level?โ€

Minimum Path Sum = โ€œWhatโ€™s the lowest score I can finish with?โ€

Both games have the same rules:

  • โžก๏ธ Move right
  • โฌ‡๏ธ Move down
  • ๐Ÿšซ No going back

๐ŸŒŸ Key Takeaways

  1. Grid DP = Table + Formula + Direction
  2. Fill the table row by row, column by column
  3. Each cell depends on its neighbors (top and left)
  4. Base cases: first row and first column are special
  5. Answer is always at the bottom-right corner

๐ŸŽ Memory Trick

โ€œRight and Down, Fill the Town!โ€

Start at top-left, move right and down, Fill each square in your DP town!

Remember: Every square remembers the best way to reach it. Thatโ€™s the magic of Dynamic Programmingโ€”building answers from smaller answers!


Now youโ€™re ready to explore any grid and find your way through! ๐Ÿ—บ๏ธโœจ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.