- Leetcode 3123. Find Edges in Shortest Paths
- 1. 解题思路
- 2. 代码实现
- 题目链接:3123. Find Edges in Shortest Paths
1. 解题思路
这一题思路上的话就是一个最短路径的求解问题,我们使用一个堆排即可对其进行实现。
不过,做题的时候挺犹豫的,因为感觉要对每一条路径保留下其历史路径,这个无论是计算开销还是存储开销都挺大的,感觉还是挺暴力的,没想到还真的成功了,也有点意外……
2. 代码实现
给出python代码实现如下:
class Solution:def findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]:graph = defaultdict(list)for i, (u, v, w) in enumerate(edges):graph[u].append((v, w, i))graph[v].append((u, w, i))ans = [False for _ in edges]distances = [math.inf for _ in range(n)]q = [(0, 0, [])]while q != []:dis, u, edges = heapq.heappop(q)if dis > distances[u]:continuedistances[u] = disfor v, w, e in graph[u]:if dis + w <= distances[v]:heapq.heappush(q, (dis+w, v, edges + [e]))if u == n-1:for e in edges:ans[e] = Truereturn ans
提交代码评测得到:耗时1911ms,占用内存50.8MB。