Drill

ProblemsPython › patterns

How many ways across the yard

mediumpatternsRecursionGridsMathPython

A forklift crosses a rectangular yard from the top-left bay to the bottom-right one, and may only ever drive right or down. Planning wants the number of distinct routes.

routes_across(rows: int, columns: int) → int

Solve it in the editor →

Where you start

def routes_across(rows: int, columns: int) -> int:
    

Worked examples

CallResult
routes_across(3, 3)6
routes_across(1, 1)1
routes_across(2, 3)3
routes_across(0, 5)0

Hint

The routes into a bay are the routes into the bay above plus the routes into the bay to its left. The top row and left column have exactly one each.

Reference solution in Python
def routes_across(rows: int, columns: int) -> int:
    if rows <= 0 or columns <= 0:
        return 0
    ways = [[1] * columns for _ in range(rows)]
    for r in range(1, rows):
        for c in range(1, columns):
            ways[r][c] = ways[r - 1][c] + ways[r][c - 1]
    return ways[rows - 1][columns - 1]

The same problem in another language

More patterns problems in Python