1use alloc::vec::Vec;
8
9use crate::graph::Vertex;
10use crate::instance::AgentId;
11use crate::path::{Time, position_at};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Conflict {
16 Vertex {
18 agents: (AgentId, AgentId),
20 vertex: Vertex,
22 time: Time,
24 },
25 Edge {
28 agents: (AgentId, AgentId),
30 from: Vertex,
32 to: Vertex,
34 time: Time,
36 },
37}
38
39impl Conflict {
40 #[must_use]
42 pub fn agents(&self) -> (AgentId, AgentId) {
43 match *self {
44 Self::Vertex { agents, .. } | Self::Edge { agents, .. } => agents,
45 }
46 }
47
48 #[must_use]
50 pub fn time(&self) -> Time {
51 match *self {
52 Self::Vertex { time, .. } | Self::Edge { time, .. } => time,
53 }
54 }
55}
56
57#[must_use]
66pub fn first_conflict<P: AsRef<[Vertex]>>(paths: &[P]) -> Option<Conflict> {
67 let mut found = None;
68 scan(paths, |conflict| {
69 found = Some(conflict);
70 false
71 });
72
73 found
74}
75
76#[must_use]
85pub fn conflicts<P: AsRef<[Vertex]>>(paths: &[P]) -> Vec<Conflict> {
86 let mut found = Vec::new();
87 scan(paths, |conflict| {
88 found.push(conflict);
89 true
90 });
91
92 found
93}
94
95fn scan<P: AsRef<[Vertex]>>(paths: &[P], mut visit: impl FnMut(Conflict) -> bool) {
97 let paths: Vec<&[Vertex]> = paths.iter().map(AsRef::as_ref).collect();
98 let horizon = paths.iter().map(|path| path.len()).max().unwrap_or(0);
99 let horizon = Time::try_from(horizon).expect("path lengths fit in u32 time steps");
100
101 for time in 0..horizon {
102 if !scan_time(&paths, time, &mut visit) {
103 return;
104 }
105 }
106}
107
108fn scan_time(paths: &[&[Vertex]], time: Time, visit: &mut impl FnMut(Conflict) -> bool) -> bool {
111 for (i, a) in paths.iter().enumerate() {
112 for (j, b) in paths.iter().enumerate().skip(i + 1) {
113 let pair = conflicts_at(a, b, (i, j), time);
114 if pair.into_iter().flatten().any(|conflict| !visit(conflict)) {
115 return false;
116 }
117 }
118 }
119
120 true
121}
122
123fn conflicts_at(
126 a: &[Vertex],
127 b: &[Vertex],
128 agents: (AgentId, AgentId),
129 time: Time,
130) -> [Option<Conflict>; 2] {
131 let (a_now, b_now) = (position_at(a, time), position_at(b, time));
132 let (a_next, b_next) = (position_at(a, time + 1), position_at(b, time + 1));
133
134 let vertex = (a_now == b_now).then_some(Conflict::Vertex {
135 agents,
136 vertex: a_now,
137 time,
138 });
139 let swap = (a_now != a_next && a_now == b_next && a_next == b_now).then_some(Conflict::Edge {
140 agents,
141 from: a_now,
142 to: a_next,
143 time,
144 });
145
146 [vertex, swap]
147}