mapf_search/graph.rs
1//! The graph agents move on: the [`Graph`] trait over dense [`Vertex`] ids, explicit
2//! [`AdjacencyList`]s and 4-connected [`Grid`]s.
3
4mod grid;
5
6use alloc::collections::VecDeque;
7use alloc::vec;
8use alloc::vec::Vec;
9
10pub use grid::Grid;
11
12/// A vertex id. Graphs number their vertices densely as `0..vertex_count()`.
13pub type Vertex = usize;
14
15/// A finite directed graph over vertices `0..vertex_count()`.
16///
17/// Agents move along edges or wait in place; waits are implicit and must not be reported
18/// as self-loops. For undirected graphs, report every edge in both directions.
19pub trait Graph {
20 /// The number of vertices. Vertex ids are `0..vertex_count()`.
21 fn vertex_count(&self) -> usize;
22
23 /// Calls `emit` once for every out-neighbour of `vertex`.
24 ///
25 /// `vertex` is always below [`Graph::vertex_count`].
26 fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex));
27}
28
29/// The direction an agent faces on an [`OrientedGraph`], below
30/// [`OrientedGraph::heading_count`].
31pub type Heading = usize;
32
33/// A [`Graph`] on which agents face a heading and only move forward, for solvers that model
34/// turning in place as taking time ([`pibt_turns`](crate::pibt_turns())).
35///
36/// Each step an agent either moves to [`OrientedGraph::forward`] of its vertex and heading,
37/// keeping the heading, or turns in place to one of [`OrientedGraph::turns`], or waits.
38/// The out-neighbours of a vertex in [`Graph::neighbors`] must be exactly the vertices
39/// some heading moves forward to, so that a vertex path alone still describes where an
40/// agent is; a turn is a wait in it.
41pub trait OrientedGraph: Graph {
42 /// The number of headings. Headings are `0..heading_count()`, the same at every vertex.
43 fn heading_count(&self) -> usize;
44
45 /// The vertex an agent at `vertex` facing `heading` reaches by moving forward, or
46 /// `None` if there is no edge that way.
47 fn forward(&self, vertex: Vertex, heading: Heading) -> Option<Vertex>;
48
49 /// Calls `emit` once for every heading one turn away from `heading`. Turning must be
50 /// able to reach every heading from every other.
51 fn turns(&self, heading: Heading, emit: impl FnMut(Heading));
52}
53
54/// A graph stored as one list of out-neighbours per vertex.
55#[derive(Debug, Clone, PartialEq, Eq, Default)]
56pub struct AdjacencyList {
57 /// `adjacency[v]` lists the out-neighbours of `v`. Every entry is below
58 /// `adjacency.len()`.
59 adjacency: Vec<Vec<Vertex>>,
60}
61
62impl AdjacencyList {
63 /// Creates a graph with `vertex_count` vertices and the given directed edges.
64 ///
65 /// # Panics
66 ///
67 /// Panics if an edge names a vertex at or above `vertex_count`.
68 #[must_use]
69 pub fn directed(vertex_count: usize, edges: &[(Vertex, Vertex)]) -> Self {
70 let mut adjacency = vec![Vec::new(); vertex_count];
71 for &(from, to) in edges {
72 assert!(
73 from < vertex_count && to < vertex_count,
74 "edge ({from}, {to}) names a vertex outside 0..{vertex_count}"
75 );
76 adjacency[from].push(to);
77 }
78
79 Self { adjacency }
80 }
81
82 /// Creates a graph with `vertex_count` vertices where every edge goes both ways.
83 ///
84 /// # Panics
85 ///
86 /// Panics if an edge names a vertex at or above `vertex_count`.
87 #[must_use]
88 pub fn undirected(vertex_count: usize, edges: &[(Vertex, Vertex)]) -> Self {
89 let both: Vec<_> = edges.iter().flat_map(|&(a, b)| [(a, b), (b, a)]).collect();
90
91 Self::directed(vertex_count, &both)
92 }
93}
94
95impl Graph for AdjacencyList {
96 fn vertex_count(&self) -> usize {
97 self.adjacency.len()
98 }
99
100 fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex)) {
101 self.adjacency[vertex].iter().copied().for_each(emit);
102 }
103}
104
105/// Exact distances, in edges, from every vertex to `target`; `None` where `target` is
106/// unreachable.
107///
108/// Breadth-first search backwards along reversed edges. Costs `O(V + E)` time and memory.
109pub(crate) fn distances_to<G: Graph + ?Sized>(graph: &G, target: Vertex) -> Vec<Option<u32>> {
110 let reverse = reverse_adjacency(graph);
111 let mut distance = vec![None; graph.vertex_count()];
112 let mut queue = VecDeque::from([target]);
113 distance[target] = Some(0);
114
115 while let Some(vertex) = queue.pop_front() {
116 let next = distance[vertex].map(|d: u32| d + 1);
117 for &previous in &reverse[vertex] {
118 if distance[previous].is_none() {
119 distance[previous] = next;
120 queue.push_back(previous);
121 }
122 }
123 }
124
125 distance
126}
127
128/// The in-neighbours of every vertex.
129pub(crate) fn reverse_adjacency<G: Graph + ?Sized>(graph: &G) -> Vec<Vec<Vertex>> {
130 let mut reverse = vec![Vec::new(); graph.vertex_count()];
131 for from in 0..graph.vertex_count() {
132 graph.neighbors(from, |to| reverse[to].push(from));
133 }
134
135 reverse
136}