mapf_search/graph/
grid.rs1use alloc::vec;
4use alloc::vec::Vec;
5
6use super::{Graph, Vertex};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Grid {
12 width: usize,
14 height: usize,
16 blocked: Vec<bool>,
18}
19
20impl Grid {
21 #[must_use]
27 pub fn new(width: usize, height: usize) -> Self {
28 assert!(width > 0 && height > 0, "a grid needs at least one cell");
29
30 Self {
31 width,
32 height,
33 blocked: vec![false; width * height],
34 }
35 }
36
37 #[must_use]
46 pub fn parse(rows: &[&str]) -> Self {
47 let width = rows.first().map_or(0, |row| row.len());
48 let mut grid = Self::new(width, rows.len());
49
50 for (y, row) in rows.iter().enumerate() {
51 assert_eq!(row.len(), width, "row {y} has a different length");
52 for (x, cell) in row.chars().enumerate() {
53 match cell {
54 '.' => {}
55 '@' => grid.block(x, y),
56 other => panic!("unknown grid cell {other:?} at ({x}, {y})"),
57 }
58 }
59 }
60
61 grid
62 }
63
64 pub fn block(&mut self, x: usize, y: usize) {
70 let vertex = self.vertex(x, y);
71 self.blocked[vertex] = true;
72 }
73
74 #[must_use]
76 pub fn width(&self) -> usize {
77 self.width
78 }
79
80 #[must_use]
82 pub fn height(&self) -> usize {
83 self.height
84 }
85
86 #[must_use]
92 pub fn vertex(&self, x: usize, y: usize) -> Vertex {
93 assert!(
94 x < self.width && y < self.height,
95 "cell ({x}, {y}) is outside the grid"
96 );
97
98 y * self.width + x
99 }
100
101 #[must_use]
103 pub fn cell(&self, vertex: Vertex) -> (usize, usize) {
104 (vertex % self.width, vertex / self.width)
105 }
106
107 #[must_use]
109 pub fn is_blocked(&self, vertex: Vertex) -> bool {
110 self.blocked[vertex]
111 }
112}
113
114impl Graph for Grid {
115 fn vertex_count(&self) -> usize {
116 self.blocked.len()
117 }
118
119 fn neighbors(&self, vertex: Vertex, mut emit: impl FnMut(Vertex)) {
120 if self.is_blocked(vertex) {
121 return;
122 }
123
124 let (x, y) = self.cell(vertex);
125 let candidates = [
126 x.checked_sub(1).map(|left| (left, y)),
127 (x + 1 < self.width).then_some((x + 1, y)),
128 y.checked_sub(1).map(|up| (x, up)),
129 (y + 1 < self.height).then_some((x, y + 1)),
130 ];
131
132 for (nx, ny) in candidates.into_iter().flatten() {
133 let next = self.vertex(nx, ny);
134 if !self.is_blocked(next) {
135 emit(next);
136 }
137 }
138 }
139}