use alloc::collections::BTreeSet;
use alloc::vec::Vec;
use crate::graph::Vertex;
use crate::mdd::Mdd;
use crate::path::{Path, Time};
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();
let mut successors = Vec::new();
self.combine(time, ¤t, &mut Vec::new(), &mut successors);
for next in successors {
if self.reach_goal(time + 1, next) {
return true;
}
}
self.trail.pop();
false
}
fn combine(
&self,
time: Time,
nodes: &[usize],
picked: &mut Vec<usize>,
out: &mut Vec<Vec<usize>>,
) {
let agent = picked.len();
if agent == self.mdds.len() {
out.push(picked.clone());
return;
}
for &child in self.mdds[agent].children(time, nodes[agent]) {
if !self.collides(time, nodes, picked, child) {
picked.push(child);
self.combine(time, nodes, picked, out);
picked.pop();
}
}
}
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();
while path.len() > 1 && path[path.len() - 2] == path[path.len() - 1] {
path.pop();
}
path
})
.collect()
}
}