We can use Dynamic Programming to solve this problem. Here dpijdp_{ij} denotes the minimum possible cost needed to move the token to the cell (i,j)(i,j).

To calculate dpijdp_{ij} Let,
PP = min of dpiy+T+(jy)dp_{iy}+T+(j-y) for yy in range [jL,j1][j-L,j-1]
QQ = min of dpxj+T+(ix)dp_{xj}+T+(i-x) for xx in range [iL,i1][i-L,i-1]

(Considering the valid cells inside the grid and those which don’t require building a bridge over a blocked cell).

Now, dpijdp_{ij} = min(P,Q)min(P,Q)

dpiy+T+(jy)dp_{iy}+T+(j-y) can be written as (dpiyy)+(T+j)(dp_{iy}-y)+(T+j) for yy in range [jL,j1][j-L,j-1]. As (T+j)(T+j) is not dependent on the previous cells, we are interested in the minimum value of (dpiyy)(dp_{iy}-y) for yy in the range [jL,j1][j-L,j-1].

Now to get the minimum value, we can maintain a monotonic deque(similar to monotonic queues, but allows us to pop elements from both ends) and store (dpijj)(dp_{ij}-j) for the relevant cells among all the cells we visit.

QQ can be retrieved in the same manner but we need MM deques for MM columns.

Using monotonic deques we can get an O(NM)O(NM) solution.

Author’s solution: https://ideone.com/wO7IUJ

Here is a blog on monotonic queue if you are not familiar with it: https://jojozhuang.github.io/algorithm/data-structure-monotonic-queue/

Contributors

Statistics

71% Solution Ratio
Soumya1Earliest, Apr '22
borisalFastest, 0.0s
MrBrionixLightest, 14 MB
MrBrionixShortest, 1341B
Toph uses cookies. By continuing you agree to our Cookie Policy.