mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
添加 0096.城市间货物运输III python3 SPFA版本
This commit is contained in:
@ -703,6 +703,9 @@ public class Main {
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
Bellman-Ford方法求解单源有限最短路
|
||||
|
||||
```python
|
||||
def main():
|
||||
# 輸入
|
||||
@ -736,6 +739,48 @@ def main():
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
SPFA方法求解单源有限最短路
|
||||
|
||||
```python
|
||||
from collections import deque
|
||||
from math import inf
|
||||
|
||||
|
||||
def main():
|
||||
n, m = [int(i) for i in input().split()]
|
||||
graph = [[] for _ in range(n+1)]
|
||||
for _ in range(m):
|
||||
v1, v2, val = [int(i) for i in input().split()]
|
||||
graph[v1].append([v2, val])
|
||||
src, dst, k = [int(i) for i in input().split()]
|
||||
min_dist = [inf for _ in range(n+1)]
|
||||
min_dist[src] = 0 # 初始化起点的距离
|
||||
que = deque([src])
|
||||
|
||||
while k != -1 and que:
|
||||
visited = [False for _ in range(n+1)] # 用于保证每次松弛时一个节点最多加入队列一次
|
||||
que_size = len(que)
|
||||
temp_dist = min_dist.copy() # 用于记录上一次遍历的结果
|
||||
for _ in range(que_size):
|
||||
cur_node = que.popleft()
|
||||
for next_node, val in graph[cur_node]:
|
||||
if min_dist[next_node] > temp_dist[cur_node] + val:
|
||||
min_dist[next_node] = temp_dist[cur_node] + val
|
||||
if not visited[next_node]:
|
||||
que.append(next_node)
|
||||
visited[next_node] = True
|
||||
k -= 1
|
||||
|
||||
if min_dist[dst] == inf:
|
||||
print("unreachable")
|
||||
else:
|
||||
print(min_dist[dst])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
Reference in New Issue
Block a user