Add generic simple dijkstra method.
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Mikael CAPELLE
2024-12-18 09:01:31 +01:00
parent 954ef1e6ce
commit 146d025d41
2 changed files with 128 additions and 56 deletions

View File

@@ -1,81 +1,58 @@
import heapq
from typing import Any, Iterator, TypeAlias, cast
from typing import Any, Iterator
from ..base import BaseSolver
Node: TypeAlias = tuple[int, int]
def dijkstra(
grid: list[Node],
n_rows: int,
n_cols: int,
start: Node = (0, 0),
target: Node | None = None,
) -> tuple[Node, ...] | None:
corrupted = set(grid)
target = target or (n_rows - 1, n_cols - 1)
queue: list[tuple[int, Node, tuple[Node, ...]]] = [(0, start, (start,))]
preds: dict[Node, tuple[Node, ...]] = {}
while queue:
dis, node, path = heapq.heappop(queue)
if node in preds:
continue
preds[node] = path
if node == target:
break
row, col = node
for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
row_n, col_n = row + dr, col + dc
if (
0 <= row_n < n_rows
and 0 <= col_n < n_cols
and (row_n, col_n) not in corrupted
and (row_n, col_n) not in preds
):
heapq.heappush(
queue, (dis + 1, (row_n, col_n), path + ((row_n, col_n),))
)
return preds.get(target, None)
from ..tools import graphs
class Solver(BaseSolver):
def print_grid(self, grid: list[tuple[int, int]], n_rows: int, n_cols: int):
values = set(grid)
for row in range(n_rows):
self.logger.info(
"".join("#" if (row, col) in values else "." for col in range(n_cols))
if self.files:
self.files.create(
"graph.txt",
"\n".join(
"".join(
"#" if (row, col) in values else "." for col in range(n_cols)
)
for row in range(n_rows)
).encode(),
text=True,
)
else:
for row in range(n_rows):
self.logger.info(
"".join(
"#" if (row, col) in values else "." for col in range(n_cols)
)
)
def dijkstra(self, corrupted: list[tuple[int, int]], n_rows: int, n_cols: int):
return graphs.dijkstra(
(0, 0),
(n_rows - 1, n_cols - 1),
graphs.make_neighbors_grid_fn(n_rows, n_cols, set(corrupted)),
)
def solve(self, input: str) -> Iterator[Any]:
values = [
cast(tuple[int, int], tuple(map(int, row.split(","))))
for row in input.splitlines()
(int(p[0]), int(p[1])) for r in input.splitlines() if (p := r.split(","))
]
n_rows, n_cols = (7, 7) if len(values) < 100 else (71, 71)
_is_test = len(values) < 100
n_rows, n_cols, n_bytes_p1 = (7, 7, 12) if _is_test else (71, 71, 1024)
n_bytes_p1 = 12 if len(values) < 100 else 1024
bytes_p1 = values[:n_bytes_p1]
self.print_grid(bytes_p1, n_rows, n_cols)
path_p1 = dijkstra(bytes_p1, n_rows, n_cols)
assert path_p1 is not None
yield len(path_p1) - 1
path_p1, cost_p1 = self.dijkstra(bytes_p1, n_rows, n_cols) or ((), -1)
yield cost_p1
path = path_p1
for b in range(n_bytes_p1, len(values)):
if values[b] not in path:
continue
path = dijkstra(values[: b + 1], n_rows, n_cols)
path, _ = self.dijkstra(values[: b + 1], n_rows, n_cols) or (None, -1)
if path is None:
yield ",".join(map(str, values[b]))
break