Can anyone tell why my algorithm is wrong?

后端 未结 1 1486
忘掉有多难
忘掉有多难 2021-01-28 09:28

I was working on single source shortest path problem and I made a modification to bfs that can solve the problem. The algorithm runs in O(2E) times, I just can\'t understand why

1条回答
  •  一生所求
    2021-01-28 10:14

    In Dijkstra's algorithm, the priority queue ensures that you don't process a vertex until you know it's distance from the source.

    BFS doesn't have this property. If the shortest path to a vertex has more than edges than the path with the fewest edges, then it will be processed too early.

    Consider this graph, for example, when you want the shortest path from S to T:

    S--5--C--1--T
    |     |
    1     1
    |     |
    A--1--B
    

    Vertex C will be visited before vertex B. You will think the distance to C is 5, because you haven't discovered the shorter path. When C is visited, it will assign a distance of 6 to T. This is incorrect, and will never be fixed, because C will not be visited again.

    0 讨论(0)
提交回复
热议问题