Question: There is an m x n grid ( 0 <= m, n <= 500). Each cell in the grid contains k coins (k could be negative or 0 too). You start from 0, 0 and end at m-1, n-1, and you can move either 1 step down or 1 step right, collecting as many coins as you can. If k < 0, then that particular cell has a robber and you can’t move into that cell. If you move into any of the 8 neighboring cells, you will be robbed of k coins. How many coins will you have when you reach m-1, n-1 ?
For example in the grid:
0,23,20,-32
13,14,44,-44
23,19,41,9
46,27,20,0
ans = 129 (by following the path: 0-13-23-46-27-20-0)
Time limit: 5 sec
I don’t think this program can be solved using dynamic programming. And I haven’t studied graph theory (in case it could be used to solve this problem). The straightforward recursive approach is the only thing I can think of, which is too inefficient under the given constraints.
So what would be a good approach to solve it? Don’t just post code, tell me how to begin. If its related to graph theory, then indicating which theorem is involved would be very useful.
Why not? This is a prime candidate for the dynamic programming approach.
Can you build a recursive solution that solves, say, a 5×5 grid? Perfect! Start with that, and then memoize it by adding an
MxNarray of best results for cells which you have already solved. Start that array with all large negative values, and then update it when you find a solution that is better. than what’s there already. Once you ‘ve finished with the cell, put the solution into theMxNarray: the next time you come there recursively, check the array for a number, and if a value is there, return it without continuing with the recursion.The memoized solution itself is rather straightforward. The preprocessing step of the algorithm (subtracting negative numbers from neighboring cells) takes more code.
Here is the solution on ideone, it returns
129as expected.