use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{Reach, SearchSpace};
mod transposition;
use transposition::{NoTable, Table, Transpositions};
pub fn dfs<G, T>(graph: &G, start: G::State, goal: &T, budget: impl Budget<Stats>) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
dfs_multi(graph, [start], goal, budget)
}
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
pub fn dfs_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
mut budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
let (mut space, start_goal) = SearchSpace::seed(starts, goal);
let mut stats = Stats::default();
let finish = |outcome, stats| SearchResult { outcome, stats };
if let Some(found) = start_goal {
return finish(Outcome::Found(space.solution(found)), stats);
}
let mut stack: Vec<_> = (0..space.len()).rev().collect();
let mut buffer = Vec::new();
while let Some(node) = stack.pop() {
if budget.exhausted(&stats) {
return finish(Outcome::LimitReached, stats);
}
stats.expanded += 1;
stats.generated += collect_successors(graph, space.state(node), &mut buffer);
let first_new = stack.len();
for (action, state, cost) in buffer.drain(..) {
let Reach::New(id) = space.reach(state, node, action, cost, false) else {
continue;
};
if goal.is_goal(space.state(id)) {
return finish(Outcome::Found(space.solution(id)), stats);
}
stack.push(id);
}
stack[first_new..].reverse();
}
finish(Outcome::Unsolvable, stats)
}
pub fn depth_limited_dfs<G, T>(
graph: &G,
start: G::State,
goal: &T,
limit: usize,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
depth_limited_dfs_multi(graph, [start], goal, limit, budget)
}
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
pub fn depth_limited_dfs_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
limit: usize,
mut budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
let roots = distinct(starts);
let mut stats = Stats::default();
if let Some(solution) = goal_root(&roots, goal) {
return SearchResult {
outcome: Outcome::Found(solution),
stats,
};
}
let probe = probe_roots(
graph,
&roots,
goal,
&mut stats,
&mut budget,
|_, _, depth| {
if depth > limit {
Bound::Prune(G::Cost::ZERO)
} else {
Bound::Open
}
},
);
let outcome = match probe {
Probe::Found(solution) => Outcome::Found(solution),
Probe::Exhausted(None) => Outcome::Unsolvable,
Probe::Exhausted(Some(_)) => Outcome::Cutoff,
Probe::Stopped => Outcome::LimitReached,
};
SearchResult { outcome, stats }
}
pub fn iddfs<G, T>(
graph: &G,
start: G::State,
goal: &T,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
iddfs_multi(graph, [start], goal, budget)
}
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
pub fn iddfs_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
mut budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
let roots = distinct(starts);
let mut stats = Stats::default();
if let Some(solution) = goal_root(&roots, goal) {
return SearchResult {
outcome: Outcome::Found(solution),
stats,
};
}
for limit in 0.. {
let probe = probe_roots(
graph,
&roots,
goal,
&mut stats,
&mut budget,
|_, _, depth| {
if depth > limit {
Bound::Prune(G::Cost::ZERO)
} else {
Bound::Open
}
},
);
let outcome = match probe {
Probe::Exhausted(Some(_)) => continue,
Probe::Found(solution) => Outcome::Found(solution),
Probe::Exhausted(None) => Outcome::Unsolvable,
Probe::Stopped => Outcome::LimitReached,
};
return SearchResult { outcome, stats };
}
unreachable!("depth limits never run out")
}
pub fn ida_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
ida_star_multi(graph, [start], goal, heuristic, budget)
}
pub fn ida_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
run_ida(graph, starts, goal, heuristic, NoTable, budget)
}
pub fn ida_star_tt<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
capacity: usize,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
ida_star_tt_multi(graph, [start], goal, heuristic, capacity, budget)
}
pub fn ida_star_tt_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
capacity: usize,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
run_ida(graph, starts, goal, heuristic, Table::new(capacity), budget)
}
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
fn run_ida<G, T, H, X>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
mut heuristic: H,
mut table: X,
mut budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
X: Transpositions<G::State, G::Cost>,
{
let roots = distinct(starts);
let mut stats = Stats::default();
if let Some(solution) = goal_root(&roots, goal) {
return SearchResult {
outcome: Outcome::Found(solution),
stats,
};
}
let Some(mut threshold) = roots
.iter()
.filter_map(|root| heuristic.estimate(root))
.min()
else {
return SearchResult {
outcome: Outcome::Unsolvable,
stats,
};
};
loop {
table.next_iteration();
let probe = probe_roots(
graph,
&roots,
goal,
&mut stats,
&mut budget,
|state, g, _| {
if table.covers(state, g) {
return Bound::Dead;
}
match heuristic.estimate(state) {
None => Bound::Dead,
Some(h) if g + h > threshold => Bound::Prune(g + h),
Some(_) => {
table.record(state, g);
Bound::Open
}
}
},
);
let outcome = match probe {
Probe::Exhausted(Some(next)) => {
threshold = next;
continue;
}
Probe::Found(solution) => Outcome::Found(solution),
Probe::Exhausted(None) => Outcome::Unsolvable,
Probe::Stopped => Outcome::LimitReached,
};
return SearchResult { outcome, stats };
}
}
pub(crate) fn distinct<S: Eq>(starts: impl IntoIterator<Item = S>) -> Vec<S> {
let mut roots: Vec<S> = Vec::new();
for start in starts {
if !roots.contains(&start) {
roots.push(start);
}
}
roots
}
pub(crate) fn goal_root<S: Clone, A, C: Cost, T: Goal<S> + ?Sized>(
roots: &[S],
goal: &T,
) -> Option<Solution<S, A, C>> {
let root = roots.iter().find(|root| goal.is_goal(root))?;
Some(Solution {
states: alloc::vec![root.clone()],
actions: Vec::new(),
cost: C::ZERO,
})
}
fn probe_roots<G, T>(
graph: &G,
roots: &[G::State],
goal: &T,
stats: &mut Stats,
budget: &mut impl Budget<Stats>,
mut bound: impl FnMut(&G::State, G::Cost, usize) -> Bound<G::Cost>,
) -> Probe<G::State, G::Action, G::Cost>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
let mut pruned: Option<G::Cost> = None;
for root in roots {
match probe(graph, root.clone(), goal, stats, budget, &mut bound) {
Probe::Exhausted(value) => pruned = pruned.into_iter().chain(value).min(),
ended => return ended,
}
}
Probe::Exhausted(pruned)
}
enum Bound<C> {
Open,
Prune(C),
Dead,
}
enum Probe<S, A, C> {
Found(Solution<S, A, C>),
Exhausted(Option<C>),
Stopped,
}
struct Frame<S, A, C> {
state: S,
via: Option<(A, C)>,
g: C,
children: Option<Vec<(A, S, C)>>,
}
fn probe<G, T>(
graph: &G,
origin: G::State,
goal: &T,
stats: &mut Stats,
budget: &mut impl Budget<Stats>,
mut bound: impl FnMut(&G::State, G::Cost, usize) -> Bound<G::Cost>,
) -> Probe<G::State, G::Action, G::Cost>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
let mut pruned: Option<G::Cost> = None;
let mut keep = |value: G::Cost| {
pruned = Some(pruned.map_or(
value,
|old| {
if value.cmp(&old).is_lt() { value } else { old }
},
));
};
let root = Frame {
state: origin,
via: None,
g: G::Cost::ZERO,
children: None,
};
match bound(&root.state, root.g, 0) {
Bound::Dead => return Probe::Exhausted(None),
Bound::Prune(value) => return Probe::Exhausted(Some(value)),
Bound::Open if goal.is_goal(&root.state) => return Probe::Found(path(&[root])),
Bound::Open => {}
}
let mut stack = alloc::vec![root];
while let Some(top) = stack.last_mut() {
if top.children.is_none() {
if budget.exhausted(stats) {
return Probe::Stopped;
}
let mut children = Vec::new();
stats.expanded += 1;
stats.generated += collect_successors(graph, &top.state, &mut children);
children.reverse();
top.children = Some(children);
}
let parent_g = top.g;
let Some((action, child, cost)) = top.children.as_mut().and_then(Vec::pop) else {
stack.pop();
continue;
};
if stack.iter().any(|frame| frame.state == child) {
continue;
}
let g = parent_g + cost;
match bound(&child, g, stack.len()) {
Bound::Dead => {}
Bound::Prune(value) => keep(value),
Bound::Open => {
let found = goal.is_goal(&child);
stack.push(Frame {
state: child,
via: Some((action, cost)),
g,
children: None,
});
if found {
return Probe::Found(path(&stack));
}
}
}
}
Probe::Exhausted(pruned)
}
fn path<S: Clone, A: Clone, C: Cost>(frames: &[Frame<S, A, C>]) -> Solution<S, A, C> {
let states = frames.iter().map(|frame| frame.state.clone()).collect();
let actions = frames
.iter()
.filter_map(|frame| frame.via.as_ref().map(|(action, _)| action.clone()))
.collect();
let cost = frames
.iter()
.filter_map(|frame| frame.via.as_ref().map(|&(_, cost)| cost))
.fold(C::ZERO, |sum, cost| sum + cost);
Solution {
states,
actions,
cost,
}
}