Python 3D Academyবাংলা

Paths through a grid

🌍 In real life. A delivery rider starts at the top-left corner of a neighbourhood whose streets form a grid, and the shop is at the bottom-right corner. To waste no time, they only ever ride east (right) or south (down). One block is closed for roadworks. How many different routes are there? And if every block has a toll, which route is cheapest?

The idea in one sentence: in a 2D DP the state is two numbers, here the square (r, c), and the table is a grid: every route to a square arrives from the square above it or the one to its left, so dp[r][c] is built from those two cells, filled row by row from the top-left.

Its words:

  • state (r, c): the row and the column of a square; dp[r][c] holds the answer for that square
  • the last move: the move that entered the square, down from above or right from the left
  • wall: a closed square; no route goes through it, so it holds 0
  • fill order: row by row, left to right, so the cells above and to the left are always ready

Counting routes, step by step:

  1. make a grid dp the size of the map
  2. the start square holds 1, and a wall holds 0
  3. every other square: dp[r][c] = dp[r − 1][c] + dp[r][c − 1], where a square off the map counts 0
  4. the answer is the bottom-right cell

Watch the routes add up round the closed block at (1, 1):

Why adding the two neighbours counts every route once. Sort the routes to (r, c) by their last move. Those that came down are exactly the routes to (r − 1, c), each with one more step; those that came right are the routes to (r, c − 1). No route is in both groups, and none is missed, so the two counts simply add.

The cheapest route. Now each square has a toll (the small number), and the rider pays the toll of every square on the route, the first and the last included. The same last-move argument gives dp[r][c] = toll + min(dp[r − 1][c], dp[r][c − 1]). To see the route itself, not just its price, walk back from the end, each time to the neighbour the value came from:

What it costs, by counting. One cell per square and two lookups each: a 1,000 × 1,000 city is 1,000,000 cells and about 2,000,000 lookups. Listing every route instead is hopeless: even a 20 × 20 grid has 35,345,263,800 routes from corner to corner. In Big-O: an R × C grid takes O(R × C) time and O(R × C) memory for the table.

def count_paths(grid):
    R, C = len(grid), len(grid[0])
    dp = [[0] * C for _ in range(R)]           # dp[r][c]: the paths from the top-left to (r, c)
    for r in range(R):
        for c in range(C):
            if grid[r][c] == "#":
                continue                       # a wall: 0 paths
            if r == 0 and c == 0:
                dp[r][c] = 1                   # the walk starts here
            else:
                above = dp[r - 1][c] if r > 0 else 0
                left = dp[r][c - 1] if c > 0 else 0
                dp[r][c] = above + left        # the last move came down or right
    return dp[R - 1][C - 1]

def min_path_sum(cost):
    R, C = len(cost), len(cost[0])
    dp = [[0] * C for _ in range(R)]           # dp[r][c]: the least it costs to reach (r, c)
    for r in range(R):
        for c in range(C):
            if r == 0 and c == 0:
                dp[r][c] = cost[0][0]
            elif r == 0:
                dp[r][c] = cost[r][c] + dp[r][c - 1]    # the top row: only from the left
            elif c == 0:
                dp[r][c] = cost[r][c] + dp[r - 1][c]    # the left column: only from above
            else:
                dp[r][c] = cost[r][c] + min(dp[r - 1][c], dp[r][c - 1])
    return dp[R - 1][C - 1]

print(count_paths(["....", ".#..", "...."]))
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))

Mistakes and edge cases.

  • row 0 and column 0: they have only one neighbour; reading dp[-1][c] doesn't raise an error in Python, it quietly reads the last row
  • walls on the first row: every square after a wall on row 0 has 0 routes, because it can only be reached from the left
  • a closed start: if the top-left square is a wall, there are 0 routes
  • rows and columns swapped: grid[r][c] is row r, column c; len(grid) is the number of rows
  • greedy steps: moving to the cheaper neighbour each time can walk into an expensive corner; only the table looks ahead

Quiz

  1. Moving only right or down, where can the last move into (r, c) come from?

    • (r − 1, c) or (r, c − 1)
    • Any of its four neighbours
    • Only (r − 1, c − 1)
  2. What does this print?

    def count_paths(grid):
        R, C = len(grid), len(grid[0])
        dp = [[0] * C for _ in range(R)]           # dp[r][c]: the paths from the top-left to (r, c)
        for r in range(R):
            for c in range(C):
                if grid[r][c] == "#":
                    continue                       # a wall: 0 paths
                if r == 0 and c == 0:
                    dp[r][c] = 1                   # the walk starts here
                else:
                    above = dp[r - 1][c] if r > 0 else 0
                    left = dp[r][c - 1] if c > 0 else 0
                    dp[r][c] = above + left        # the last move came down or right
        return dp[R - 1][C - 1]
    
    print(count_paths(["...", "...", "..."]))
  3. What does this print?

    def count_paths(grid):
        R, C = len(grid), len(grid[0])
        dp = [[0] * C for _ in range(R)]           # dp[r][c]: the paths from the top-left to (r, c)
        for r in range(R):
            for c in range(C):
                if grid[r][c] == "#":
                    continue                       # a wall: 0 paths
                if r == 0 and c == 0:
                    dp[r][c] = 1                   # the walk starts here
                else:
                    above = dp[r - 1][c] if r > 0 else 0
                    left = dp[r][c - 1] if c > 0 else 0
                    dp[r][c] = above + left        # the last move came down or right
        return dp[R - 1][C - 1]
    
    print(count_paths(["..#", "..."]))
  4. How many cells does the table for a 300 × 400 grid fill?

    • 120,000: one per square
    • 700: one per row and column
    • As many as there are routes
  5. min_path_sum([[1, 2], [3, 4]]) should be 7 but gives 3. Which line is wrong?

    def min_path_sum(cost):
        R, C = len(cost), len(cost[0])
        dp = [[0] * C for _ in range(R)]
        for r in range(R):
            for c in range(C):
                if r == 0 and c == 0:
                    dp[r][c] = cost[0][0]
                elif r == 0:
                    dp[r][c] = cost[r][c] + dp[r][c - 1]
                elif c == 0:
                    dp[r][c] = cost[r][c] + dp[r - 1][c]
                else:
                    dp[r][c] = min(dp[r - 1][c], dp[r][c - 1])
        return dp[R - 1][C - 1]

Coding tasks

  1. Write count_paths(grid): grid is a list of equal-length strings, "." for an open square and "#" for a wall. Return how many routes go from the top-left square to the bottom-right one moving only right or down, never through a wall.

  2. Write min_path_sum(cost): cost is a grid of tolls (a list of equal-length lists). Moving only right or down from the top-left square to the bottom-right one, and paying the toll of every square you stand on (both ends included), return the least you can pay.