51 lines
1.1 KiB
Python
51 lines
1.1 KiB
Python
from collections import deque
|
|
from strategies.strategy import PathFindingStrategy
|
|
|
|
|
|
class BFSStrategy(PathFindingStrategy):
|
|
|
|
def findPath(self, maze, start, exit):
|
|
|
|
frontier = deque([start])
|
|
|
|
visited = {
|
|
start.getPosition()
|
|
}
|
|
|
|
ancestry = {}
|
|
|
|
explored_count = 0
|
|
|
|
while frontier:
|
|
|
|
current = frontier.popleft()
|
|
explored_count += 1
|
|
|
|
if current == exit:
|
|
break
|
|
|
|
for neighbor in maze.getNeighbors(current):
|
|
|
|
mark = neighbor.getPosition()
|
|
|
|
if mark in visited:
|
|
continue
|
|
|
|
visited.add(mark)
|
|
ancestry[mark] = current
|
|
frontier.append(neighbor)
|
|
|
|
if exit.getPosition() not in visited:
|
|
return [], explored_count
|
|
|
|
route = []
|
|
cursor = exit
|
|
|
|
while cursor != start:
|
|
route.append(cursor)
|
|
cursor = ancestry[cursor.getPosition()]
|
|
|
|
route.append(start)
|
|
route.reverse()
|
|
|
|
return route, explored_count |