Grid.getPath_BFS()
This commit is contained in:
parent
642a32b884
commit
2692f4b560
@ -1,4 +1,5 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
from collections import deque
|
||||||
from .aoc_ocr import convert_array_6
|
from .aoc_ocr import convert_array_6
|
||||||
from .coordinate import Coordinate, DistanceAlgorithm, Shape
|
from .coordinate import Coordinate, DistanceAlgorithm, Shape
|
||||||
from .types import Numeric
|
from .types import Numeric
|
||||||
@ -144,7 +145,7 @@ class Grid:
|
|||||||
return len(self.__grid)
|
return len(self.__grid)
|
||||||
|
|
||||||
def count(self, value: Any) -> int:
|
def count(self, value: Any) -> int:
|
||||||
return len([x for x in self.values() if x == value])
|
return list(self.__grid.values()).count(value)
|
||||||
|
|
||||||
def isSet(self, pos: Coordinate) -> bool:
|
def isSet(self, pos: Coordinate) -> bool:
|
||||||
return pos in self.__grid
|
return pos in self.__grid
|
||||||
@ -286,6 +287,39 @@ class Grid:
|
|||||||
else:
|
else:
|
||||||
raise NotImplementedError(mode)
|
raise NotImplementedError(mode)
|
||||||
|
|
||||||
|
def getPath_BFS(self, pos_from: Coordinate, pos_to: Coordinate, includeDiagonal: bool, walls: List[Any] = None,
|
||||||
|
stop_at_first: Any = None) -> Union[None, List[Coordinate]]:
|
||||||
|
queue = deque()
|
||||||
|
came_from = {pos_from: None}
|
||||||
|
queue.append(pos_from)
|
||||||
|
if walls is None:
|
||||||
|
walls = [self.__default]
|
||||||
|
|
||||||
|
while queue:
|
||||||
|
current = queue.popleft()
|
||||||
|
found_end = False
|
||||||
|
for c in self.getNeighboursOf(current, includeDiagonal=includeDiagonal, includeDefault=self.__default not in walls):
|
||||||
|
if c in came_from and self.get(c) in walls:
|
||||||
|
continue
|
||||||
|
came_from[c] = current
|
||||||
|
if c == pos_to or (stop_at_first is not None and self.get(c) == stop_at_first):
|
||||||
|
pos_to = c
|
||||||
|
found_end = True
|
||||||
|
break
|
||||||
|
queue.append(c)
|
||||||
|
if found_end:
|
||||||
|
break
|
||||||
|
|
||||||
|
if pos_to not in came_from:
|
||||||
|
return None
|
||||||
|
|
||||||
|
ret = []
|
||||||
|
while pos_to in came_from:
|
||||||
|
ret.insert(0, pos_to)
|
||||||
|
pos_to = came_from[pos_to]
|
||||||
|
|
||||||
|
return ret
|
||||||
|
|
||||||
def getPath(self, pos_from: Coordinate, pos_to: Coordinate, includeDiagonal: bool, walls: List[Any] = None,
|
def getPath(self, pos_from: Coordinate, pos_to: Coordinate, includeDiagonal: bool, walls: List[Any] = None,
|
||||||
weighted: bool = False) -> Union[None, List[Coordinate]]:
|
weighted: bool = False) -> Union[None, List[Coordinate]]:
|
||||||
f_costs = []
|
f_costs = []
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user