Skip to main content

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/// A graph stored as one list of out-neighbours per vertex.
30#[derive(Debug, Clone, PartialEq, Eq, Default)]
31pub struct AdjacencyList {
32    /// `adjacency[v]` lists the out-neighbours of `v`. Every entry is below
33    /// `adjacency.len()`.
34    adjacency: Vec<Vec<Vertex>>,
35}
36
37impl AdjacencyList {
38    /// Creates a graph with `vertex_count` vertices and the given directed edges.
39    ///
40    /// # Panics
41    ///
42    /// Panics if an edge names a vertex at or above `vertex_count`.
43    #[must_use]
44    pub fn directed(vertex_count: usize, edges: &[(Vertex, Vertex)]) -> Self {
45        let mut adjacency = vec![Vec::new(); vertex_count];
46        for &(from, to) in edges {
47            assert!(
48                from < vertex_count && to < vertex_count,
49                "edge ({from}, {to}) names a vertex outside 0..{vertex_count}"
50            );
51            adjacency[from].push(to);
52        }
53
54        Self { adjacency }
55    }
56
57    /// Creates a graph with `vertex_count` vertices where every edge goes both ways.
58    ///
59    /// # Panics
60    ///
61    /// Panics if an edge names a vertex at or above `vertex_count`.
62    #[must_use]
63    pub fn undirected(vertex_count: usize, edges: &[(Vertex, Vertex)]) -> Self {
64        let both: Vec<_> = edges.iter().flat_map(|&(a, b)| [(a, b), (b, a)]).collect();
65
66        Self::directed(vertex_count, &both)
67    }
68}
69
70impl Graph for AdjacencyList {
71    fn vertex_count(&self) -> usize {
72        self.adjacency.len()
73    }
74
75    fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex)) {
76        self.adjacency[vertex].iter().copied().for_each(emit);
77    }
78}
79
80/// Exact distances, in edges, from every vertex to `target`; `None` where `target` is
81/// unreachable.
82///
83/// Breadth-first search backwards along reversed edges. Costs `O(V + E)` time and memory.
84pub(crate) fn distances_to<G: Graph + ?Sized>(graph: &G, target: Vertex) -> Vec<Option<u32>> {
85    let reverse = reverse_adjacency(graph);
86    let mut distance = vec![None; graph.vertex_count()];
87    let mut queue = VecDeque::from([target]);
88    distance[target] = Some(0);
89
90    while let Some(vertex) = queue.pop_front() {
91        let next = distance[vertex].map(|d: u32| d + 1);
92        for &previous in &reverse[vertex] {
93            if distance[previous].is_none() {
94                distance[previous] = next;
95                queue.push_back(previous);
96            }
97        }
98    }
99
100    distance
101}
102
103/// The in-neighbours of every vertex.
104pub(crate) fn reverse_adjacency<G: Graph + ?Sized>(graph: &G) -> Vec<Vec<Vertex>> {
105    let mut reverse = vec![Vec::new(); graph.vertex_count()];
106    for from in 0..graph.vertex_count() {
107        graph.neighbors(from, |to| reverse[to].push(from));
108    }
109
110    reverse
111}