I'm trying to make a pathfinding algorithm for my project. I need it for a simulation and I need it to be fast!!!
I watched a few videos explaining the algorithm online and came up with the code below.
However, the performance varies a lot considering the start/finish points. My project should have grids that go upwards of 500x500
A very slow example is the following, with a very small grid:
I have no idea what's making the algorithm so slow
Dir_Map = {
"1": (1, 0),
"2": (0, 1),
"3": (-1, 0),
"4": (0, -1),
"5": (1, 1),
"6": (-1, -1),
"7": (1, -1),
"8": (-1, 1)
}
class Node():
def __init__(self, pos):
self.x = pos[0]
self.y = pos[1]
self.g = 0
self.h = 0
self.f = 0
self.beggining = 1
self.parent = None
def update(self, final):
self.h = manhattan(self, final)
self.f = self.f + self.g
class Child(Node):
def __init__(self, x, y, parent):
Node.__init__(self, (parent.x + x, parent.y + y))
self.g = abs(x) + abs(y) + parent.g
self.beggining = 0
self.came_from = (parent.x, parent.y)
self.parent = parent
def sortbyF(node):
return node.f
def manhattan(current, final):
return abs(current.x - final.x) + abs(current.y - final.y)
def check_List(list, successor):
for ind, val in enumerate(list):
if (val.x, val.y) == (successor.x, successor.y):
if val.f < successor.f:
return 1
return 0
openlist = []
closedlist = []
def recursion(node):
if node.beggining is 0:
closedlist.append(node.came_from)
recursion(node.parent)
def pfind(grid, start, finish):
start_node = Node((start[0], start[1]))
finish_node = Node((finish[0], finish[1]))
Stop = 0
openlist.append(start_node)
while len(openlist) is not 0:
current = openlist.pop(0)
for dirs in Dir_Map.values():
suc = Child(dirs[0], dirs[1], current)
if grid[suc.x][suc.y] is not 1 and suc.x <= len(grid[:][1]) and suc.y <= len(grid[1][:]):
suc.update(finish_node)
if (suc.x, suc.y) == finish:
#Added so it adds the last step.
#New suc.came_from = finish
suc = Child(dirs[0], dirs[1], suc)
#retrace the path.
recursion(suc)
closedlist.reverse()
return closedlist
if check_List(openlist, suc):
continue
openlist.append(suc)
else:
continue
openlist.sort(key=sortbyF)
return None
grid = [[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]
print(pfind(grid, (0,0), (4,3)))
self.f = self.f + self.g
Methinks one of those fs should be a h. \$\endgroup\$