Skip to content

Commit eae7eab

Browse files
committed
Fixed 1135.
1 parent c08e05d commit eae7eab

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

leetcode/medium/1135_connecting_cities_with_minimum_cost.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ The pseudocode could be represented as such:
2121
- Select the edge with the min weight of an unvisited vertex from top of heap.
2222
- Add the selected vertex to the visited vertices.
2323
- Add selected vertex's neighboring edges of unvisited vertices into the heap.
24-
24+
2525
Since we are sorting based on vertices, the sorting will take log(V) run-time.
2626
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.
2727
That is why its O((V+E) log(V)) run-time.
@@ -31,14 +31,14 @@ from collections import defaultdict
3131
3232
class Solution:
3333
def minimumCost(self, N: int, connections: List[List[int]]) -> int:
34-
34+
3535
def create_adj_list(connections):
3636
adj_list = defaultdict(list)
3737
for city1, city2, cost in connections:
3838
adj_list[city1].append(Vertex(city2, cost))
3939
adj_list[city2].append(Vertex(city1, cost))
4040
return adj_list
41-
41+
4242
adj_list = create_adj_list(connections)
4343
visited = set([N])
4444
min_heap = list(adj_list[N] if N in adj_list else [])
@@ -51,18 +51,19 @@ class Solution:
5151
visited.add(vertex.to)
5252
min_cost += vertex.cost
5353
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)
5556
return min_cost if len(visited) == N else -1
56-
57+
5758
class Vertex(object):
58-
59+
5960
def __init__(self, to, cost):
6061
self.to = to
6162
self.cost = cost
62-
63+
6364
def __lt__(self, other):
6465
return self.cost < other.cost
65-
66+
6667
def __repr__(self):
6768
return 'To: {}, Cost: {}'.format(self.to, self.cost)
6869
```

0 commit comments

Comments
 (0)