Skip to content

Commit

Permalink
perf: optimize dijkstra all_paths using reference insteadof cloning
Browse files Browse the repository at this point in the history
  • Loading branch information
manhunto committed Dec 23, 2024
1 parent 205d3a1 commit 8e0d3bb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
| [Day 13: Claw Contraption](src/solutions/year2024/day13.rs) | ⭐⭐ | 0.241 | 0.331 |
| [Day 14: Restroom Redoubt](src/solutions/year2024/day14.rs) | ⭐⭐ | 0.172 | 102.252 |
| [Day 15: Warehouse Woes](src/solutions/year2024/day15.rs) | ⭐⭐ | 7.226 | 9.084 |
| [Day 16: Reindeer Maze](src/solutions/year2024/day16.rs) | ⭐⭐ | 6.478 | 74.105 |
| [Day 16: Reindeer Maze](src/solutions/year2024/day16.rs) | ⭐⭐ | 6.478 | 24.347 |
| [Day 17: Chronospatial Computer](src/solutions/year2024/day17.rs) | - | - | - |
| [Day 18: RAM Run](src/solutions/year2024/day18.rs) | ⭐⭐ | 2.487 | 204.885 |
| [Day 19: Linen Layout](src/solutions/year2024/day19.rs) | ⭐⭐ | 2.923 | 22.751 |
Expand Down
33 changes: 18 additions & 15 deletions src/utils/graphs/dijkstra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ impl<'a, T> Dijkstra<'a, T> {
Self::visit(
start,
*end,
Vec::new(),
VecDeque::new(),
&mut Vec::new(),
&mut VecDeque::new(),
&mut paths,
come_from,
);
Expand All @@ -137,29 +137,32 @@ impl<'a, T> Dijkstra<'a, T> {
fn visit(
from: T,
end: T,
mut visited: Vec<T>,
mut path: VecDeque<T>,
visited: &mut Vec<T>,
path: &mut VecDeque<T>,
paths: &mut Vec<VecDeque<T>>,
come_from: &HashMap<T, Vec<T>>,
) where
T: Hash + Eq + PartialEq + Ord + Debug + Copy,
{
{
visited.push(end);
path.push_front(end);
visited.push(end);
path.push_front(end);

if from == end {
paths.push(path.clone());
if from == end {
paths.push(path.clone());
path.pop_front();
visited.pop();

return;
}
return;
}

for p in come_from.get(&end).unwrap_or(&Vec::new()) {
if !visited.contains(p) {
Self::visit(from, *p, visited.clone(), path.clone(), paths, come_from);
}
for p in come_from.get(&end).unwrap_or(&Vec::new()) {
if !visited.contains(p) {
Self::visit(from, *p, visited, path, paths, come_from);
}
}

path.pop_front();
visited.pop();
}
}

Expand Down

0 comments on commit 8e0d3bb

Please sign in to comment.