What is the time complexity if it needs to revisit visited nodes in BFS?

不打扰是莪最后的温柔 提交于 2019-12-11 07:56:41

问题


I am working on an algorithm problem.

For Simplification, the problem could be reduced to:

Given an m * n matrix, with a bunch of special points, find an optimal path from point A to point B in this matrix. The optimal path is a path which passes fewest special points. If there are multiple paths with fewest special points, choose the shortest one. If there are still multiple paths, select one randomly among them.

This problem could definitely be solved by BFS. To hold a queue, record information of each point. If a better path is found, update information and put this point into the queue. Output information at point B at last.

The tricky part is a point may be revisited multiple times and I cannot estimate the time complexity in this case. Can anyone help me with it?


回答1:


The ultimate goal is to not hit any special points or as less as possible. You can use Dijkstra for that with following settings: Ordinary edge costs 1. The edge between special point and all other costs more than m*n (therefore even if you go through the whole maze without special node, its better than go one step, but through special node).

Then you run Dijsktra and you have it. As you have graph with maximum amount of edges per node (its matrix, so 4 directions at maximum) the number of edges is approximatelly 4*m*n which is O(m*n).

So your V=(m*n) and E=O(m*n) and Dijkstra is O(V + E*log E). Just put it there and you get O(m*n + m*n * log(m*n)) = O(m*n*log(m*n))



来源:https://stackoverflow.com/questions/50877949/what-is-the-time-complexity-if-it-needs-to-revisit-visited-nodes-in-bfs

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