use alloc::vec;
use alloc::vec::Vec;
use super::{Graph, Heading, OrientedGraph, Vertex};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grid {
width: usize,
height: usize,
blocked: Vec<bool>,
}
impl Grid {
#[must_use]
pub fn new(width: usize, height: usize) -> Self {
assert!(width > 0 && height > 0, "a grid needs at least one cell");
Self {
width,
height,
blocked: vec![false; width * height],
}
}
#[must_use]
pub fn parse(rows: &[&str]) -> Self {
let width = rows.first().map_or(0, |row| row.len());
let mut grid = Self::new(width, rows.len());
for (y, row) in rows.iter().enumerate() {
assert_eq!(row.len(), width, "row {y} has a different length");
for (x, cell) in row.chars().enumerate() {
match cell {
'.' => {}
'@' => grid.block(x, y),
other => panic!("unknown grid cell {other:?} at ({x}, {y})"),
}
}
}
grid
}
pub fn block(&mut self, x: usize, y: usize) {
let vertex = self.vertex(x, y);
self.blocked[vertex] = true;
}
#[must_use]
pub fn width(&self) -> usize {
self.width
}
#[must_use]
pub fn height(&self) -> usize {
self.height
}
#[must_use]
pub fn vertex(&self, x: usize, y: usize) -> Vertex {
assert!(
x < self.width && y < self.height,
"cell ({x}, {y}) is outside the grid"
);
y * self.width + x
}
#[must_use]
pub fn cell(&self, vertex: Vertex) -> (usize, usize) {
(vertex % self.width, vertex / self.width)
}
#[must_use]
pub fn is_blocked(&self, vertex: Vertex) -> bool {
self.blocked[vertex]
}
}
impl Grid {
pub const EAST: Heading = 0;
pub const NORTH: Heading = 1;
pub const WEST: Heading = 2;
pub const SOUTH: Heading = 3;
}
impl OrientedGraph for Grid {
fn heading_count(&self) -> usize {
4
}
fn forward(&self, vertex: Vertex, heading: Heading) -> Option<Vertex> {
if self.is_blocked(vertex) {
return None;
}
let (x, y) = self.cell(vertex);
let (nx, ny) = match heading {
Self::EAST => (x + 1, y),
Self::NORTH => (x, y.checked_sub(1)?),
Self::WEST => (x.checked_sub(1)?, y),
Self::SOUTH => (x, y + 1),
_ => return None,
};
if nx >= self.width || ny >= self.height {
return None;
}
let next = self.vertex(nx, ny);
(!self.is_blocked(next)).then_some(next)
}
fn turns(&self, heading: Heading, mut emit: impl FnMut(Heading)) {
emit((heading + 1) % 4);
emit((heading + 3) % 4);
}
}
impl Graph for Grid {
fn vertex_count(&self) -> usize {
self.blocked.len()
}
fn neighbors(&self, vertex: Vertex, mut emit: impl FnMut(Vertex)) {
if self.is_blocked(vertex) {
return;
}
let (x, y) = self.cell(vertex);
let candidates = [
x.checked_sub(1).map(|left| (left, y)),
(x + 1 < self.width).then_some((x + 1, y)),
y.checked_sub(1).map(|up| (x, up)),
(y + 1 < self.height).then_some((x, y + 1)),
];
for (nx, ny) in candidates.into_iter().flatten() {
let next = self.vertex(nx, ny);
if !self.is_blocked(next) {
emit(next);
}
}
}
}