A robot is located at the top-left corner of an m x n
grid (the starting point is marked as Start
in the figure below).
The robot can only move either down or to the right at a time, and is trying to reach the bottom-right corner of the grid (marked as Finish
in the figure below).
Start | ||||||
---|---|---|---|---|---|---|
Finish |
For example, the figure above is a 7 x 3
grid. How many possible paths are there?
It's a relatively simple dynamic programming problem. Based on the requirements of the problem, a grid can be drawn directly. It's important to note that the robot can only move down or to the right at a time. For the example of a 7 x 3
grid provided in the problem, the following grid can be drawn.
1 | 1 | 1 | 1 | 1 | 1 | 1 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
1 | 3 | 6 | 10 | 15 | 21 | 28 |
By filling in the data according to the above table, we can easily find the pattern. The final value at the endpoint is simply the sum of the values of its upper and left nodes. In other words, it can be solved using a two-dimensional array and the dynamic programming equation dp[i][j] = dp[i-1][j] + dp[i][j-1]
. Finally, return the value of the last element in this array. First, initialize the array by generating a m * n
array using a constructor and filling it with 0
. The reason for filling the outer array with 0
is that map
will skip empty array slots. You can fill the outer array with any value, because the return value of the map
callback function will override it. Then define a loop. If a certain index is 0
in the loop, then fill it with 1
, otherwise add the value of the upper node and the left node to that point. This constructs the aforementioned table, and finally return the value of the last element in the table.