refactor 81 and dijkstra
This commit is contained in:
+40
-10
@@ -6,6 +6,30 @@ type Coordinate = (usize, usize);
|
||||
|
||||
const START: Coordinate = (0, 0);
|
||||
|
||||
pub enum AllowedMovements {
|
||||
DownRight,
|
||||
DownRightUp,
|
||||
}
|
||||
|
||||
impl AllowedMovements {
|
||||
fn get_neighbours(&self, c: &Coordinate) -> Vec<Coordinate> {
|
||||
match self {
|
||||
Self::DownRight => self.get_neighbours_down_right(c),
|
||||
Self::DownRightUp => self.get_neighbours_down_right_up(c),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_neighbours_down_right(&self, (x0, y0): &Coordinate) -> Vec<Coordinate> {
|
||||
vec![(*x0 + 1, *y0), (*x0, *y0 + 1)]
|
||||
}
|
||||
|
||||
fn get_neighbours_down_right_up(&self, (x0, y0): &Coordinate) -> Vec<Coordinate> {
|
||||
let mut result = self.get_neighbours_down_right(&(*x0, *y0));
|
||||
result.push((*x0, *y0 - 1));
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Matrix<T>
|
||||
where
|
||||
T: Add + PartialOrd + Debug + Copy,
|
||||
@@ -26,6 +50,7 @@ pub struct Dijkstra<'a, T> {
|
||||
matrix: &'a mut dyn Matrix<T>,
|
||||
unvisited_with_distance: HashSet<Coordinate>,
|
||||
unvisited_without_distance: HashSet<Coordinate>,
|
||||
allowed_movements: AllowedMovements,
|
||||
}
|
||||
|
||||
impl<'a, T> Debug for Dijkstra<'a, T> {
|
||||
@@ -40,13 +65,14 @@ impl<'a, T> Dijkstra<'a, T>
|
||||
where
|
||||
T: PartialOrd + Add<Output = T> + Display + Copy + Debug,
|
||||
{
|
||||
pub fn new(matrix: &'a mut dyn Matrix<T>) -> Self {
|
||||
pub fn new(matrix: &'a mut dyn Matrix<T>, allowed_movements: AllowedMovements) -> Self {
|
||||
let unvisited_with_distance = HashSet::new();
|
||||
let unvisited_without_distance = Self::initialize_unvisited_set(&*matrix, START);
|
||||
Self {
|
||||
matrix,
|
||||
unvisited_with_distance,
|
||||
unvisited_without_distance,
|
||||
allowed_movements,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,15 +105,19 @@ where
|
||||
}
|
||||
|
||||
fn get_neighbours(&self, coordinate: &Coordinate) -> Vec<Coordinate> {
|
||||
let (x0, y0) = coordinate;
|
||||
let mut result = vec![];
|
||||
if *x0 < self.matrix.width() - 1 {
|
||||
result.push((*x0 + 1, *y0));
|
||||
}
|
||||
if *y0 < self.matrix.height() - 1 {
|
||||
result.push((*x0, *y0 + 1));
|
||||
}
|
||||
result
|
||||
let possible_neighbours = self.allowed_movements.get_neighbours(coordinate);
|
||||
self.remove_out_of_bounds_neighbours(possible_neighbours)
|
||||
}
|
||||
|
||||
fn remove_out_of_bounds_neighbours(&self, neighbours: Vec<Coordinate>) -> Vec<Coordinate> {
|
||||
neighbours
|
||||
.into_iter()
|
||||
.filter(|c| self.is_in_bounds(c))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_in_bounds(&self, (x, y): &Coordinate) -> bool {
|
||||
*x < self.matrix.width() && *y < self.matrix.height()
|
||||
}
|
||||
|
||||
fn update_neighbour(&mut self, next: Coordinate, previous: Coordinate, previous_distance: T) {
|
||||
|
||||
Reference in New Issue
Block a user