@@ -82,15 +82,14 @@ def getDistance(pos, pos2):
8282
8383def getPath (start , end ):
8484 openList = [start ]
85- distance = {str (start ) : 0 }
85+ nodes = {str (start ) : [ '' , 0 ]} # nodes['[x, y]'] = [parent, distance from the start]
8686 closedList = []
87- parents = {}
8887
8988 while len (openList ) != 0 :
9089
9190 current = openList [0 ]
9291 for tmp in openList :
93- if distance [str (tmp )] + getDistance (tmp , end ) < distance [str (current )] + getDistance (current , end ):
92+ if nodes [str (tmp )][ 1 ] + getDistance (tmp , end ) < nodes [str (current )][ 1 ] + getDistance (current , end ):
9493 current = tmp
9594
9695 if current == end :
@@ -106,21 +105,18 @@ def getPath(start, end):
106105 continue
107106 elif not [X ,Y ] in openList :
108107 openList .append ([X ,Y ])
109- parents [str ([X ,Y ])] = current
110- distance [str ([X ,Y ])] = distance [str (current )] + 1
111- else :
112- if not str ([X ,Y ]) in parents or distance [str ([X ,Y ])] > distance [str (current )] + 1 :
113- parents [str ([X ,Y ])] = current
114- distance [str ([X ,Y ])] = distance [str (current )] + 1
108+ nodes [str ([X ,Y ])] = [current , nodes [str (current )][1 ] + 1 ]
109+ elif not str ([X ,Y ]) in nodes or nodes [str ([X ,Y ])][1 ] > nodes [str (current )][1 ] + 1 :
110+ nodes [str ([X ,Y ])] = [current , nodes [str (current )][1 ] + 1 ]
115111
116112 if current != end : # if the path does not exist
117113 return - 1
118114
119- tmp = parents [str (end )]
115+ tmp = nodes [str (end )][ 0 ]
120116 path = []
121- while tmp != start :
117+ while tmp != start : # rewind the parents of the nodes to get the path
122118 path .append (tmp )
123- tmp = parents [str (tmp )]
119+ tmp = nodes [str (tmp )][ 0 ]
124120 return path [::- 1 ]
125121
126122
0 commit comments