Python coding

Count routes around blocked cells

A robot starts on the top-left cell of grid (a list of equal-length strings) and must reach the bottom-right cell, moving one cell right or one cell down at a time. . is a free cell and # is a blocked one, where the robot can never stand. Return the number of different routes.

The grid has 1 to 15 rows and columns. If the start or the finish is blocked, there are no routes.

Besides the tests, one large input (a 12 × 13 open grid) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_routes(["...",".#.","..."]) → 2
  • count_routes(["..#.","....",".#..","...."]) → 7
  • count_routes([".#","#."]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every route into a cell arrives from the cell above or the cell to its left, so ways[r][c] = ways[r-1][c] + ways[r][c-1] for a free cell, and 0 for a blocked one.

Hint 2

Seed the start with 1 and fill row by row. One row of counts is enough: before you update it, ways[c] still holds the value from the row above.

Hint 3

Don't pre-fill the first row and column with 1s: a blocked cell there cuts off everything behind it. The start itself may be blocked too.

Solution and why it works
pythonO(R·C), R×C grid · O(C)
def count_routes(grid: list[str]) -> int:
    ways = [0] * len(grid[0])            # ways[c] = routes into column c of the current row
    ways[0] = 1                          # one way to stand on the start
    for row in grid:
        for c, cell in enumerate(row):
            if cell == "#":
                ways[c] = 0              # nothing passes through a blocked cell
            elif c > 0:
                ways[c] += ways[c - 1]   # from above (the old ways[c]) + from the left
    return ways[-1]

A route into a free cell comes from above or from the left, and those two groups never overlap, so their counts add: R × C cells at O(1) each, where plain recursion walks every route one by one. A blocked cell counts 0, so it passes nothing on. The trap is the border: filling the first row and column with 1s ignores a blocked cell there, which hides every cell behind it. A blocked start must give 0 as well.

Related lab: Big-O growth