@@ -21,7 +21,7 @@ The pseudocode could be represented as such:
21
21
- Select the edge with the min weight of an unvisited vertex from top of heap.
22
22
- Add the selected vertex to the visited vertices.
23
23
- Add selected vertex's neighboring edges of unvisited vertices into the heap.
24
-
24
+
25
25
Since we are sorting based on vertices, the sorting will take log(V) run-time.
26
26
However, we have to sort this based on number of vertices or edges because we can be given a graph of islands or nodes that have edges to all nodes.
27
27
That is why its O((V+E) log(V)) run-time.
@@ -31,14 +31,14 @@ from collections import defaultdict
31
31
32
32
class Solution:
33
33
def minimumCost(self, N: int, connections: List[List[int]]) -> int:
34
-
34
+
35
35
def create_adj_list(connections):
36
36
adj_list = defaultdict(list)
37
37
for city1, city2, cost in connections:
38
38
adj_list[city1].append(Vertex(city2, cost))
39
39
adj_list[city2].append(Vertex(city1, cost))
40
40
return adj_list
41
-
41
+
42
42
adj_list = create_adj_list(connections)
43
43
visited = set([N])
44
44
min_heap = list(adj_list[N] if N in adj_list else [])
@@ -51,18 +51,19 @@ class Solution:
51
51
visited.add(vertex.to)
52
52
min_cost += vertex.cost
53
53
for vertex in adj_list[vertex.to]:
54
- heapq.heappush(min_heap, vertex)
54
+ if vertex.to not in visited:
55
+ heapq.heappush(min_heap, vertex)
55
56
return min_cost if len(visited) == N else -1
56
-
57
+
57
58
class Vertex(object):
58
-
59
+
59
60
def __init__(self, to, cost):
60
61
self.to = to
61
62
self.cost = cost
62
-
63
+
63
64
def __lt__(self, other):
64
65
return self.cost < other.cost
65
-
66
+
66
67
def __repr__(self):
67
68
return 'To: {}, Cost: {}'.format(self.to, self.cost)
68
69
```
0 commit comments