forked from UNN/2026-rff_mp
42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
|
|
import heapq
|
||
|
|
from strategies.pathfinding_strategy import PathFindingStrategy
|
||
|
|
|
||
|
|
|
||
|
|
class DijkstraStrategy(PathFindingStrategy):
|
||
|
|
name = "Dijkstra"
|
||
|
|
|
||
|
|
def findPath(self, maze, start, exitCell):
|
||
|
|
self.visitedCount = 0
|
||
|
|
if start is None or exitCell is None:
|
||
|
|
return []
|
||
|
|
|
||
|
|
pq = [(0, start.x, start.y, start)]
|
||
|
|
dist = {(start.x, start.y): 0}
|
||
|
|
parent = {}
|
||
|
|
closed = set()
|
||
|
|
|
||
|
|
while pq:
|
||
|
|
current_cost, _, _, current = heapq.heappop(pq)
|
||
|
|
pos = (current.x, current.y)
|
||
|
|
|
||
|
|
if pos in closed:
|
||
|
|
continue
|
||
|
|
|
||
|
|
closed.add(pos)
|
||
|
|
self.visitedCount += 1
|
||
|
|
|
||
|
|
if current.x == exitCell.x and current.y == exitCell.y:
|
||
|
|
return self._restore_path(parent, start, exitCell)
|
||
|
|
|
||
|
|
for neighbor in maze.getNeighbors(current):
|
||
|
|
npos = (neighbor.x, neighbor.y)
|
||
|
|
step_cost = getattr(neighbor, "weight", 1)
|
||
|
|
new_cost = current_cost + step_cost
|
||
|
|
|
||
|
|
if new_cost < dist.get(npos, float("inf")):
|
||
|
|
dist[npos] = new_cost
|
||
|
|
parent[npos] = current
|
||
|
|
heapq.heappush(pq, (new_cost, neighbor.x, neighbor.y, neighbor))
|
||
|
|
|
||
|
|
return []
|