mod grid;
use alloc::collections::VecDeque;
use alloc::vec;
use alloc::vec::Vec;
pub use grid::Grid;
pub type Vertex = usize;
pub trait Graph {
fn vertex_count(&self) -> usize;
fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex));
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AdjacencyList {
adjacency: Vec<Vec<Vertex>>,
}
impl AdjacencyList {
#[must_use]
pub fn directed(vertex_count: usize, edges: &[(Vertex, Vertex)]) -> Self {
let mut adjacency = vec![Vec::new(); vertex_count];
for &(from, to) in edges {
assert!(
from < vertex_count && to < vertex_count,
"edge ({from}, {to}) names a vertex outside 0..{vertex_count}"
);
adjacency[from].push(to);
}
Self { adjacency }
}
#[must_use]
pub fn undirected(vertex_count: usize, edges: &[(Vertex, Vertex)]) -> Self {
let both: Vec<_> = edges.iter().flat_map(|&(a, b)| [(a, b), (b, a)]).collect();
Self::directed(vertex_count, &both)
}
}
impl Graph for AdjacencyList {
fn vertex_count(&self) -> usize {
self.adjacency.len()
}
fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex)) {
self.adjacency[vertex].iter().copied().for_each(emit);
}
}
pub(crate) fn distances_to<G: Graph + ?Sized>(graph: &G, target: Vertex) -> Vec<Option<u32>> {
let reverse = reverse_adjacency(graph);
let mut distance = vec![None; graph.vertex_count()];
let mut queue = VecDeque::from([target]);
distance[target] = Some(0);
while let Some(vertex) = queue.pop_front() {
let next = distance[vertex].map(|d: u32| d + 1);
for &previous in &reverse[vertex] {
if distance[previous].is_none() {
distance[previous] = next;
queue.push_back(previous);
}
}
}
distance
}
pub(crate) fn reverse_adjacency<G: Graph + ?Sized>(graph: &G) -> Vec<Vec<Vertex>> {
let mut reverse = vec![Vec::new(); graph.vertex_count()];
for from in 0..graph.vertex_count() {
graph.neighbors(from, |to| reverse[to].push(from));
}
reverse
}