use alloc::collections::BTreeSet;
use alloc::vec::Vec;
use crate::graph::Vertex;
use crate::mdd::Mdd;
use crate::path::{Path, Time, trim_trailing_waits};
pub(crate) fn joint_paths(mdds: &[&Mdd]) -> Option<Vec<Path>> {
let depth = mdds.iter().map(|mdd| mdd.depth()).max().unwrap_or(0);
let mut search = Search {
mdds,
depth,
visited: BTreeSet::new(),
trail: Vec::new(),
};
let start = alloc::vec![0; mdds.len()];
if !search.reach_goal(0, start) {
return None;
}
Some(search.paths())
}
struct Search<'a> {
mdds: &'a [&'a Mdd],
depth: Time,
visited: BTreeSet<(Time, Vec<usize>)>,
trail: Vec<Vec<usize>>,
}
impl Search<'_> {
fn reach_goal(&mut self, time: Time, nodes: Vec<usize>) -> bool {
if !self.visited.insert((time, nodes.clone())) {
return false;
}
self.trail.push(nodes);
if time == self.depth {
return true;
}
let current = self.trail.last().expect("just pushed").clone();
if self.descend(time, ¤t, &mut Vec::with_capacity(current.len())) {
return true;
}
self.trail.pop();
false
}
fn descend(&mut self, time: Time, nodes: &[usize], picked: &mut Vec<usize>) -> bool {
let agent = picked.len();
if agent == self.mdds.len() {
return self.reach_goal(time + 1, picked.clone());
}
let mdds = self.mdds;
for &child in mdds[agent].children(time, nodes[agent]) {
if self.collides(time, nodes, picked, child) {
continue;
}
picked.push(child);
if self.descend(time, nodes, picked) {
return true;
}
picked.pop();
}
false
}
fn collides(&self, time: Time, nodes: &[usize], picked: &[usize], child: usize) -> bool {
let me = picked.len();
let (from, to) = (
self.vertex(me, time, nodes[me]),
self.vertex(me, time + 1, child),
);
picked.iter().enumerate().any(|(other, &their_child)| {
let their_from = self.vertex(other, time, nodes[other]);
let their_to = self.vertex(other, time + 1, their_child);
their_to == to || (from != to && their_from == to && their_to == from)
})
}
fn vertex(&self, agent: usize, time: Time, index: usize) -> Vertex {
self.mdds[agent].level(time)[index]
}
fn paths(&self) -> Vec<Path> {
(0..self.mdds.len())
.map(|agent| {
let mut path: Path = (0..)
.zip(&self.trail)
.map(|(time, nodes)| self.vertex(agent, time, nodes[agent]))
.collect();
trim_trailing_waits(&mut path);
path
})
.collect()
}
}