We can use Dynamic Programming to solve this problem. Here denotes the minimum possible cost needed to move the token to the cell .
To calculate Let,
= min of for in range
= min of for in range
(Considering the valid cells inside the grid and those which don’t require building a bridge over a blocked cell).
Now, =
can be written as for in range . As is not dependent on the previous cells, we are interested in the minimum value of for in the range .
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 for the relevant cells among all the cells we visit.
can be retrieved in the same manner but we need deques for columns.
Using monotonic deques we can get an 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/