Interview-Harry Potter walk through matrix.

LiBlog發表於2014-12-24

假設你是harry potter,在grid的左上角,你現在要走到右下角,grid中有正數也有負數,遇到正數表示你的strength增加那麼多,遇到負數表示strength減少那麼多,在任何時刻如果你的strength小於等於0,那麼你就掛了。在一開始你有一定的初始的strength,現在問這個初始的strength最少是多少,才能保證你能夠找到一條路走到右下角。每一步只能向右或者向下。

http://www.mitbbs.com/article_t1/JobHunting/32611137_0_1.html

Analysis:

Assume d[i][j] means that after reaching grid[i][j], how much strength you should have at least to reach the goal. Then we have formula:

d[i][j] = min{d[i+1][j]-grid[i+1][j], d[i][j+1]-grid[i][j+1]} or 0 if the min value is less than 0.

The negtive value of min{d[i+1][j]-grid[i+1][j], d[i][j+1]-grid[i][j+1]} means that you actually need negtive strength to reach the goal starting at grid[i][j] because there is path whose accumulative strength is positive. However, you cannot have negtive strength at d[i][j], because d[i][j] also means that how much strength you should accumlate when you walk from (0,0) to (i,j) so that you can reach the goal through (i,j). From this sense, a negtive value is not permitted, since you need reach grid[i][j]. In other word, for any i,j, we always have d[i][j] >=0 .

 

相關文章