1mod grid;
5
6use alloc::collections::VecDeque;
7use alloc::vec;
8use alloc::vec::Vec;
9
10pub use grid::Grid;
11
12pub type Vertex = usize;
14
15pub trait Graph {
20 fn vertex_count(&self) -> usize;
22
23 fn neighbors(&self, vertex: Vertex, emit: impl FnMut(Vertex));
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
31pub struct AdjacencyList {
32 adjacency: Vec<Vec<Vertex>>,
35}
36
37impl AdjacencyList {
38 #[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 #[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
80pub(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
103pub(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}