How many ways across the yard
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.
- Movement is only ever one bay right or one bay down.
- Return how many distinct routes reach the far corner.
- A yard with no rows or no columns has no routes.
- A single bay is already the destination: one route.
routesAcross(rows: int, columns: int) → int
Go 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.
Where you start
func routesAcross(rows int, columns int) int {
}
Worked examples
| Call | Result |
|---|---|
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 Go
func routesAcross(rows int, columns int) int {
if rows <= 0 || columns <= 0 {
return 0
}
ways := make([][]int, rows)
for r := range ways {
ways[r] = make([]int, columns)
for c := range ways[r] {
if r == 0 || c == 0 {
ways[r][c] = 1
} else {
ways[r][c] = ways[r-1][c] + ways[r][c-1]
}
}
}
return ways[rows-1][columns-1]
}