Imagine a climber trying to climb on top of a wall. A wall is constructed out of square blocks of equal size. From each block, the climber can reach three blocks of the row right above: one right on top, one to the right and one to the left ( unless right or left not available because that is end of the wall ).
Find the least costly path from bottom to top where cost is the summation of costs of the blocks used on the path.
Problem Representation: An NxM size grid where each cell has a positive cost C(i,j) associated with it. There exists three possible moves from a cell (i,j) -
- i+1,j-1 [ diagonally left ]
- i+1. j [ above ]
- i+1.j+1 [ diagonally right ]
Take an array dp[ n ][ m ] that will hold the cost for all cells. Initiate dp[ 0 ][ i ] = C(0,i) for 0 ≤ i ≤ m. There are three cases to the recurrence: a cell might be in the middle (horizontally), on the leftmost or on the rightmost sides of the grid. Thus, we compute dp[ i ][ j ] as follows-
After all iteration, result is min( dp[ n ][ i ] ) for all 0 ≤ i ≤ m. To get the actuall path, call a function pathfinder recursively.
Problems to solve: Philosopher's Stone , Tri graphs
Comments
Post a Comment