use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Goal};
use crate::best_first::GraphResult;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub fn bfs<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,
{
bfs_multi(graph, [start], goal, budget)
}
pub fn bfs_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 counters = Stats::default();
let (mut space, start_goal) = SearchSpace::seed(starts, goal);
if let Some(found) = start_goal {
return finish(Outcome::Found(space.solution(found)), counters);
}
let mut queue: VecDeque<NodeId> = (0..space.len()).collect();
let mut buffer = Vec::new();
while let Some(node) = queue.pop_front() {
if budget.exhausted(&counters) {
return finish(Outcome::LimitReached, counters);
}
counters.expanded += 1;
counters.generated += collect_successors(graph, space.state(node), &mut buffer);
if let Some(found) = enqueue_new(&mut space, &mut queue, &mut buffer, node, goal) {
return finish(Outcome::Found(space.solution(found)), counters);
}
}
finish(Outcome::Unsolvable, counters)
}
fn enqueue_new<S, A, C, T>(
space: &mut SearchSpace<S, A, C>,
queue: &mut VecDeque<NodeId>,
buffer: &mut Vec<(A, S, C)>,
parent: NodeId,
goal: &T,
) -> Option<NodeId>
where
S: Hash + Eq,
C: crate::Cost,
T: Goal<S> + ?Sized,
{
for (action, state, cost) in buffer.drain(..) {
let Reach::New(id) = space.reach(state, parent, action, cost, false) else {
continue;
};
if goal.is_goal(space.state(id)) {
return Some(id);
}
queue.push_back(id);
}
None
}
fn finish<S, A, C>(outcome: Outcome<S, A, C>, stats: Stats) -> SearchResult<S, A, C> {
SearchResult { outcome, stats }
}