@@ -162,7 +162,10 @@ def add_walls(self, vertices):
162
162
for vertex in vertices :
163
163
if vertex in self .edges :
164
164
del self .edges [vertex ]
165
- self .vertices .remove (vertex )
165
+ if isinstance (self .vertices , list ):
166
+ self .vertices .remove (vertex )
167
+ else :
168
+ del self .vertices [vertex ]
166
169
changed = True
167
170
168
171
self .edges = {
@@ -489,6 +492,7 @@ def dijkstra(self, start, end=None):
489
492
heapq .heapify (frontier )
490
493
self .distance_from_start = {start : 0 }
491
494
self .came_from = {start : None }
495
+ min_distance = float ("inf" )
492
496
493
497
while frontier :
494
498
current_distance , vertex = heapq .heappop (frontier )
@@ -497,6 +501,10 @@ def dijkstra(self, start, end=None):
497
501
if not neighbors :
498
502
continue
499
503
504
+ # No need to explore neighbors if we already found a shorter path to the end
505
+ if current_distance > min_distance :
506
+ continue
507
+
500
508
for neighbor , weight in neighbors .items ():
501
509
# We've already checked that node, and it's not better now
502
510
if neighbor in self .distance_from_start and self .distance_from_start [
@@ -511,6 +519,9 @@ def dijkstra(self, start, end=None):
511
519
self .distance_from_start [neighbor ] = current_distance + weight
512
520
self .came_from [neighbor ] = vertex
513
521
522
+ if neighbor == end :
523
+ min_distance = min (min_distance , current_distance + weight )
524
+
514
525
return end is None or end in self .distance_from_start
515
526
516
527
def a_star_search (self , start , end = None ):
0 commit comments