mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Compare commits
2 Commits
c3929a56d8
...
4240f8fc8c
| Author | SHA1 | Date | |
|---|---|---|---|
| 4240f8fc8c | |||
| 9a4ac427e0 |
@@ -69,23 +69,21 @@ impl Map {
|
|||||||
|
|
||||||
pub fn shortest_path(&self, start: Point, end: Point) -> u32 {
|
pub fn shortest_path(&self, start: Point, end: Point) -> u32 {
|
||||||
let mut todo = BinaryHeap::new();
|
let mut todo = BinaryHeap::new();
|
||||||
todo.push(Reverse((Self::manhattan(start, end), 0, start)));
|
todo.push(Reverse((0, start)));
|
||||||
|
|
||||||
let mut visited = vec![false; self.data.len()];
|
let mut best = vec![u32::MAX; self.data.len()];
|
||||||
|
|
||||||
let height = self.height() as i32;
|
let height = self.height() as i32;
|
||||||
|
|
||||||
while let Some(Reverse((_, distance, pos))) = todo.pop() {
|
while let Some(Reverse((distance, pos))) = todo.pop() {
|
||||||
if pos == end {
|
if pos == end {
|
||||||
return distance;
|
return distance;
|
||||||
}
|
}
|
||||||
|
|
||||||
if visited[self.index(pos)] {
|
if best[self.index(pos)] < distance {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
visited[self.index(pos)] = true;
|
|
||||||
|
|
||||||
let (x, y) = pos;
|
let (x, y) = pos;
|
||||||
|
|
||||||
for dy in -1..=1 {
|
for dy in -1..=1 {
|
||||||
@@ -100,15 +98,15 @@ impl Map {
|
|||||||
|
|
||||||
let new = (x + dx, y + dy);
|
let new = (x + dx, y + dy);
|
||||||
let index = self.index(new);
|
let index = self.index(new);
|
||||||
|
let new_distance = distance + self.data[index] as u32;
|
||||||
|
|
||||||
if visited[index] {
|
if best[index] <= new_distance {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let new_distance = distance + self.data[index] as u32;
|
best[index] = new_distance;
|
||||||
let new_guess = Self::manhattan(new, end) + new_distance;
|
|
||||||
|
|
||||||
todo.push(Reverse((new_guess, new_distance, new)));
|
todo.push(Reverse((new_distance, new)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,10 +114,6 @@ impl Map {
|
|||||||
panic!("No route found from {:?} to {:?}", start, end);
|
panic!("No route found from {:?} to {:?}", start, end);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn manhattan((xa, ya): Point, (xb, yb): Point) -> u32 {
|
|
||||||
(xa - xb).abs() as u32 + (ya - yb).abs() as u32
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn height(&self) -> usize {
|
pub fn height(&self) -> usize {
|
||||||
self.data.len() / self.width
|
self.data.len() / self.width
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user