Avoid queueing worse routes

This commit is contained in:
2021-12-15 18:40:20 +01:00
parent 9a4ac427e0
commit 4240f8fc8c

View File

@@ -71,7 +71,7 @@ impl Map {
let mut todo = BinaryHeap::new(); let mut todo = BinaryHeap::new();
todo.push(Reverse((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;
@@ -80,12 +80,10 @@ impl Map {
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,12 +98,13 @@ 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;
todo.push(Reverse((new_distance, new))); todo.push(Reverse((new_distance, new)));
} }