问题
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