Shorted Path - Directed Weighted Graph
Dijkstra Algorithm
Key Idea
Greedy
. UtilizePriority Queue
, to find the NEAREST node SO FAR. And calculate distance (fromstart
) to the neighbors of it. If there is SMALLER distance, update, and push that neighbor into thePriority Queue
- With
BFS
style
Time Complexity
O(ElogV)
* Each `V` should enter the PQ at least ONCE.
* For each `V`, need to calculate NEW distance (to the `start`)
* Finally, around O(ElogV)
Pre-Condition to Utilize Dijkstra
Directed Weighted graph
No negative weight. But why?
标准Dijkstra算法是计算最短路径的,但是为什么Dijkstra算法不允许存在负权重边么?
因为Dijkstra计算最短路径的正确性依赖一个前提:路径中每增加一条边,路径的总权重就会增加。
其实把这个结论反过来也是OK的:
如果想计算最长路径,路径中每增加一条边,路径的总权重就会减少。要是能够满足这个条件,也可以用Dijkstra算法。
比如LC1514
Key Points
- About the
code template
Why do we need this code piece?
This can improve the performance if a node with a larger distance get into theif distToCurrentNode > distToNode[currentNode] { continue }
priority queue
before the smallest distance
Problems
Problems | Solutions | Key Points | code | Complexity |
---|---|---|---|---|
743. Network Delay Time | Dijkstra | code | ||
1631. Path With Minimum Effort | Dijkstra | How to define and update the effortToNode array? |
code | |
1514. Path with Maximum Probability | code | |||
- | - | - | - | - |