Shortest path in matrix with obstacles with cheat paths

被刻印的时光 ゝ 提交于 2019-12-02 05:46:39

Your matrix is a representation of a graph. Without the cheat paths it is quite easy to implement a nice BFS. Implementing the cheat paths is not a big deal. Just add the same matrix as another 'layer' on top of the first one. bottom layer is 'carry', top layer is 'no carry'. You can move to the other layer only at B-points for the given cost. This is the same BFS with a third dimension.

You have n^2 nodes and (n-1)^2 edges per layer and additionally a maximum of n^2 eges connecting the layers. That's O(n^2).

You can just build a new graph with nodes labeled by (N, w) where N is a node in the original graph (so a position in your matrix), and w=0 or 1 is whether you're carrying a weight. It's then quite easy to add all possible edges in this graph

This new graph is of size 2*V, not V^2 (and the number of edges is around 4*V+number(B)).

Then you can use a shortest path algorithm, for instance Dijkstra's algorithm: complexity O(E + V log(V)) which is O(V log(V)) in your case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!