In abstract, given a 2D array find the number of paths to move from the top-left corner to the bottom right corner. The only possible moves from a cell of the grid to the next one are either down or right.
Define the structure of an optimal solution
An optimal solution is represented by the number of paths to move from the top-left corner to any other cell of the grid.
Recursively define the value of an optimal solution
The key observation is that each cell of the grid can be reached only from left or up. So, an optimal solution S for a generic cell with coordinates (i.j) is given by S(i,j) = S(i-1,j) + S(i,j-1).
Compute the value of an optimal solution
The following c++ program implements a solution according to the top-down with memoization approach:
The following python program implements a solution according to the bottom-up approach:
An extension of this problem considers that some obstacles are added to the grid, so that it’s not possible to move in a cell with an obstacle. The recurrence formula defining the value of an optimal solution is very similar to the previous one, except that S(i,j) = 0 if the cell (i,j) contains an obstacle. The following python programs solves this problem, assuming that the value of a cell is 1 if there is an onstacle and 0 otherwise:
Comments