1111class Solution :
1212 def getMinRiskValue (self , N , M , X , Y , W ):
1313
14- # Kruskal's algorithm with union-find to construct MST
14+ # Kruskal's algorithm with union-find
1515 parent = list (range (N + 1 ))
1616
1717 def find (x ):
@@ -29,30 +29,9 @@ class Solution:
2929
3030 edges = sorted (zip (W, X, Y))
3131
32- MST_edges = []
33- for edge in edges:
34- if union(edge[1 ], edge[2 ]):
35- MST_edges .append(edge)
36- if find(0 ) == find(N):
37- break
38- 39- MST = collections.defaultdict(list )
40- target = find(0 )
41- for w, u, v in MST_edges :
42- if find(u) == target and find(v) == target:
43- MST [u].append((v, w))
44- MST [v].append((u, w))
45- 46- # dfs to search route from 0 to n
47- dfs = [(0 , None , float (' -inf' ))]
48- while dfs:
49- v, p, max_w = dfs.pop()
50- for n, w in MST [v]:
51- cur_max_w = max (max_w, w)
52- if n == N:
53- return cur_max_w
54- if n != p:
55- dfs.append((n, v, cur_max_w))
32+ for w, x, y in edges:
33+ if union(x, y) and find(0 ) == find(N): # early return without constructing MST
34+ return w
5635```
5736
5837``` Python
0 commit comments