Drill

ProblemsC# › patterns

How many ways across the yard

mediumpatternsRecursionGridsMathC#

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.

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

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public int RoutesAcross(int rows, int columns) {
    
}

Worked examples

CallResult
RoutesAcross(3, 3)6
RoutesAcross(1, 1)1
RoutesAcross(2, 3)3
RoutesAcross(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 C#
public int RoutesAcross(int rows, int columns) {
    if (rows <= 0 || columns <= 0) return 0;
    var ways = new int[rows, columns];
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {
            ways[r, c] = (r == 0 || c == 0) ? 1 : ways[r - 1, c] + ways[r, c - 1];
        }
    }
    return ways[rows - 1, columns - 1];
}

The same problem in another language

More patterns problems in C#