Path Problems
A robot starts at the upper-left corner of an m-by-n grid. Each move goes one cell down or right. How many ways lead to the bottom-right corner?
Grid paths: combine routes from above and left
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
Whatever route reaches the lower-right corner, it has a last move. The destination is , so the previous cell must be or .
If X routes reach and Y routes reach , then X + Y routes reach . The original problem becomes counting routes to those two preceding cells.
This gives f[i][j] = f[i−1][j] + f[i][j−1], where f[i][j] counts the ways to reach .
Initially, f[0][0] = 1: there is one way to be at the starting cell.
On a boundary where i = 0 or j = 0, only one direction can lead to the cell, so f[i][j] = 1.
KNOWLEDGE QUIZ
Path problem
#include <stdio.h>
int path(int row, int col) {
int path[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (i == 0 || j == 0) {
path[i][j] = 1;
} else {
path[i][j] = path[i - 1][j] + path[i][j - 1];
}
}
}
return path[row - 1][col - 1];
}
int main(void) {
printf("%d\n", path(4, 8));
return 0;
}Row and column counts are positive integers. Counts for the examples fit the integer range.
KNOWLEDGE QUIZ
Fill a 3-by-4 route-count grid
| Row / column | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | — | — | — | — |
| 1 | — | — | — | — |
| 2 | — | — | — | — |
Move from (0,0) to (2,3), right or down only. Fill boundaries first, then calculate each interior cell, marking its two sources. Find the total route count.