use alloc::vec;
use search_core::NonNegF64;
use super::{Corners, RING, coordinate};
use crate::best_first::a_star;
use crate::grid::{CostGrid, GridCell, sqrt};
use crate::outcome::{Limits, Solution};
use crate::problem::Successors;
pub(super) fn cheapest<G: CostGrid>(
grid: &G,
start: GridCell,
goal: GridCell,
min_cost: f64,
) -> Option<Solution<(f64, f64), (), NonNegF64>> {
let heuristic = crate::heuristic_fn(|&corner: &GridCell| {
let (dx, dy) = (
coordinate(corner.0.abs_diff(goal.0)),
coordinate(corner.1.abs_diff(goal.1)),
);
NonNegF64::new(min_cost * sqrt(dx * dx + dy * dy))
});
let solution = a_star(
&Lattice(Corners(grid)),
start,
&|&corner: &GridCell| corner == goal,
heuristic,
Limits::NONE,
)
.into_solution()?;
Some(Solution {
actions: vec![(); solution.actions.len()],
states: solution
.states
.into_iter()
.map(|(x, y)| (coordinate(x), coordinate(y)))
.collect(),
cost: solution.cost,
})
}
struct Lattice<'g, G>(Corners<'g, G>);
impl<G: CostGrid> Successors for Lattice<'_, G> {
type State = GridCell;
type Action = ();
type Cost = NonNegF64;
fn successors(&self, &corner: &GridCell, mut emit: impl FnMut((), GridCell, NonNegF64)) {
let (neighbours, cells) = self.0.around(corner);
for (k, neighbour) in neighbours.into_iter().enumerate() {
let Some(neighbour) = neighbour else {
continue;
};
let cost = if k % 2 == 1 {
cells[k / 2] * core::f64::consts::SQRT_2
} else {
let (previous, next) = ((k + RING.len() - 1) % RING.len(), k + 1);
cells[previous / 2].min(cells[next / 2])
};
if cost.is_finite() {
emit(
(),
neighbour,
NonNegF64::new(cost).expect("cell costs are positive"),
);
}
}
}
}