From 2692f4b560f7035e73c5f1cd75e3c617e2f08756 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Wed, 14 Dec 2022 19:37:03 +0100 Subject: [PATCH] Grid.getPath_BFS() --- tools/grid.py | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/tools/grid.py b/tools/grid.py index 9312d72..40d2c03 100644 --- a/tools/grid.py +++ b/tools/grid.py @@ -1,4 +1,5 @@ from __future__ import annotations +from collections import deque from .aoc_ocr import convert_array_6 from .coordinate import Coordinate, DistanceAlgorithm, Shape from .types import Numeric @@ -144,7 +145,7 @@ class Grid: return len(self.__grid) 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: return pos in self.__grid @@ -286,6 +287,39 @@ class Grid: else: 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, weighted: bool = False) -> Union[None, List[Coordinate]]: f_costs = []