11
11
class Solution :
12
12
def getMinRiskValue (self , N , M , X , Y , W ):
13
13
14
- # Kruskal's algorithm with union-find to construct MST
14
+ # Kruskal's algorithm with union-find
15
15
parent = list (range (N + 1 ))
16
16
17
17
def find (x ):
@@ -29,30 +29,9 @@ class Solution:
29
29
30
30
edges = sorted (zip (W, X, Y))
31
31
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
56
35
```
57
36
58
37
``` Python
0 commit comments