You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: en/1-1000/743-network-delay-time.md
+79-7Lines changed: 79 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -41,7 +41,8 @@ We will send a signal from a given node `k`. Return _the **minimum** time it tak
41
41
## Intuition
42
42
We can solve it via both **Bellman-Ford algorithm** and **Dijkstra's algorithm**.
43
43
44
-
`Bellman-Ford algorithm` has less code and can handle the situation of **negative** edge weights, but it is slower than `Dijkstra's algorithm`.
44
+
`Bellman-Ford algorithm` has less code and can handle the situation of **negative** edge weights, but it is slower than `Dijkstra's algorithm` if it is not optimized.
45
+
The following code will introduce how to optimize.
45
46
46
47
`Dijkstra's algorithm` always takes the shortest path, so it is more efficient, but it requires writing more code and it cannot handle the situation of **negative** edge weights.
47
48
@@ -54,17 +55,21 @@ For a detailed description of **Dijkstra's algorithm**, please refer to [1514. P
54
55
* Time: `O(V * E)`.
55
56
* Space: `O(V)`.
56
57
58
+
### Queue-improved Bellman-Ford algorithm (also known as `Shortest Path Faster Algorithm` abbreviated as `SPFA`)
59
+
* Time: `O(V * X)` (`X` < `E`).
60
+
* Space: `O(V + E)`.
61
+
57
62
### Dijkstra's algorithm using `heap sort`
58
63
* Time: `O(E * log(E))`.
59
64
* Space: `O(V + E)`.
60
65
61
66
## Python
62
-
### Standard Bellman-Ford algorithm
67
+
### Bellman-Ford algorithm (slow, yet below, I will introduce how to improve its efficiency)
for source_node, target_node, time in edges: # process edges directly
@@ -84,12 +89,46 @@ class Solution:
84
89
return result
85
90
```
86
91
87
-
### Algorithm similar to Bellman-Ford algorithm
92
+
A very similar question: [787. Cheapest Flights Within K Stops](./787-cheapest-flights-within-k-stops.md), but if you use the above code, it will not be accepted by LeetCode.
93
+
94
+
You can try to solve `787. Cheapest Flights Within K Stops` first, then read on.
0 commit comments