@@ -162,7 +162,10 @@ def add_walls(self, vertices):
162162 for vertex in vertices :
163163 if vertex in self .edges :
164164 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 ]
166169 changed = True
167170
168171 self .edges = {
@@ -489,6 +492,7 @@ def dijkstra(self, start, end=None):
489492 heapq .heapify (frontier )
490493 self .distance_from_start = {start : 0 }
491494 self .came_from = {start : None }
495+ min_distance = float ("inf" )
492496
493497 while frontier :
494498 current_distance , vertex = heapq .heappop (frontier )
@@ -497,6 +501,10 @@ def dijkstra(self, start, end=None):
497501 if not neighbors :
498502 continue
499503
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+
500508 for neighbor , weight in neighbors .items ():
501509 # We've already checked that node, and it's not better now
502510 if neighbor in self .distance_from_start and self .distance_from_start [
@@ -511,6 +519,9 @@ def dijkstra(self, start, end=None):
511519 self .distance_from_start [neighbor ] = current_distance + weight
512520 self .came_from [neighbor ] = vertex
513521
522+ if neighbor == end :
523+ min_distance = min (min_distance , current_distance + weight )
524+
514525 return end is None or end in self .distance_from_start
515526
516527 def a_star_search (self , start , end = None ):
0 commit comments