use super::Run;
use crate::graph::{OrientedGraph, Vertex};
use crate::instance::AgentId;
impl<G: OrientedGraph> Run<'_, G> {
pub(super) fn swap_partner(&self, agent: AgentId, candidates: &[Vertex]) -> Option<AgentId> {
let here = self.here[agent];
let &first = candidates.first()?;
if first == here {
return None;
}
if let Some(other) = self.occupant[first] {
let undecided = self.claim[other].is_none() && self.decided[other].is_none();
if undecided
&& self.has_edge(first, here)
&& self.swap_required(agent, other, here, first)
&& self.room_to_back_off(first, here)
{
return Some(other);
}
}
let mut neighbors = alloc::vec::Vec::new();
self.instance
.graph()
.neighbors(here, |next| neighbors.push(next));
neighbors.into_iter().find_map(|vertex| {
let other = self.occupant[vertex]?;
let wants_through = vertex != first
&& self.has_edge(vertex, here)
&& self.swap_required(other, agent, here, first)
&& self.room_to_back_off(first, here);
wants_through.then_some(other)
})
}
fn has_edge(&self, from: Vertex, to: Vertex) -> bool {
let mut found = false;
self.instance
.graph()
.neighbors(from, |next| found |= next == to);
found
}
fn swap_required(
&self,
pusher: AgentId,
puller: AgentId,
pusher_at: Vertex,
puller_at: Vertex,
) -> bool {
let least =
|agent: AgentId, vertex: Vertex| self.costs.least(agent, vertex).unwrap_or(u32::MAX);
let (mut behind, mut ahead) = (pusher_at, puller_at);
for _ in 0..self.instance.graph().vertex_count() {
if least(pusher, ahead) >= least(pusher, behind) {
break;
}
match self.ways_on(ahead, behind) {
Ways::Open => return false,
Ways::DeadEnd => break,
Ways::One(next) => (behind, ahead) = (ahead, next),
}
}
let crosses = least(puller, behind) < least(puller, ahead);
let pusher_done_or_closer =
least(pusher, behind) == 0 || least(pusher, ahead) < least(pusher, behind);
crosses && pusher_done_or_closer
}
fn room_to_back_off(&self, away_from: Vertex, start: Vertex) -> bool {
let (mut behind, mut ahead) = (away_from, start);
for _ in 0..self.instance.graph().vertex_count() {
if ahead == away_from {
return false;
}
match self.ways_on(ahead, behind) {
Ways::Open => return true,
Ways::DeadEnd => return false,
Ways::One(next) => (behind, ahead) = (ahead, next),
}
}
false
}
fn ways_on(&self, vertex: Vertex, from: Vertex) -> Ways {
let graph = self.instance.graph();
let mut count = 0;
let mut last = None;
graph.neighbors(vertex, |next| {
if next != from && !self.is_parked_dead_end(next) {
count += 1;
last = Some(next);
}
});
match (count, last) {
(0, _) | (_, None) => Ways::DeadEnd,
(1, Some(next)) => Ways::One(next),
_ => Ways::Open,
}
}
fn is_parked_dead_end(&self, vertex: Vertex) -> bool {
let mut degree = 0;
self.instance.graph().neighbors(vertex, |_| degree += 1);
degree == 1
&& self.occupant[vertex]
.is_some_and(|agent| self.instance.agents()[agent].goal == vertex)
}
}
enum Ways {
DeadEnd,
One(Vertex),
Open,
}