Skip to content

Commit 8e0d3bb

Browse files
committed
perf: optimize dijkstra all_paths using reference insteadof cloning
1 parent 205d3a1 commit 8e0d3bb

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
| [Day 13: Claw Contraption](src/solutions/year2024/day13.rs) | ⭐⭐ | 0.241 | 0.331 |
2727
| [Day 14: Restroom Redoubt](src/solutions/year2024/day14.rs) | ⭐⭐ | 0.172 | 102.252 |
2828
| [Day 15: Warehouse Woes](src/solutions/year2024/day15.rs) | ⭐⭐ | 7.226 | 9.084 |
29-
| [Day 16: Reindeer Maze](src/solutions/year2024/day16.rs) | ⭐⭐ | 6.478 | 74.105 |
29+
| [Day 16: Reindeer Maze](src/solutions/year2024/day16.rs) | ⭐⭐ | 6.478 | 24.347 |
3030
| [Day 17: Chronospatial Computer](src/solutions/year2024/day17.rs) | - | - | - |
3131
| [Day 18: RAM Run](src/solutions/year2024/day18.rs) | ⭐⭐ | 2.487 | 204.885 |
3232
| [Day 19: Linen Layout](src/solutions/year2024/day19.rs) | ⭐⭐ | 2.923 | 22.751 |

src/utils/graphs/dijkstra.rs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,8 @@ impl<'a, T> Dijkstra<'a, T> {
123123
Self::visit(
124124
start,
125125
*end,
126-
Vec::new(),
127-
VecDeque::new(),
126+
&mut Vec::new(),
127+
&mut VecDeque::new(),
128128
&mut paths,
129129
come_from,
130130
);
@@ -137,29 +137,32 @@ impl<'a, T> Dijkstra<'a, T> {
137137
fn visit(
138138
from: T,
139139
end: T,
140-
mut visited: Vec<T>,
141-
mut path: VecDeque<T>,
140+
visited: &mut Vec<T>,
141+
path: &mut VecDeque<T>,
142142
paths: &mut Vec<VecDeque<T>>,
143143
come_from: &HashMap<T, Vec<T>>,
144144
) where
145145
T: Hash + Eq + PartialEq + Ord + Debug + Copy,
146146
{
147-
{
148-
visited.push(end);
149-
path.push_front(end);
147+
visited.push(end);
148+
path.push_front(end);
150149

151-
if from == end {
152-
paths.push(path.clone());
150+
if from == end {
151+
paths.push(path.clone());
152+
path.pop_front();
153+
visited.pop();
153154

154-
return;
155-
}
155+
return;
156+
}
156157

157-
for p in come_from.get(&end).unwrap_or(&Vec::new()) {
158-
if !visited.contains(p) {
159-
Self::visit(from, *p, visited.clone(), path.clone(), paths, come_from);
160-
}
158+
for p in come_from.get(&end).unwrap_or(&Vec::new()) {
159+
if !visited.contains(p) {
160+
Self::visit(from, *p, visited, path, paths, come_from);
161161
}
162162
}
163+
164+
path.pop_front();
165+
visited.pop();
163166
}
164167
}
165168

0 commit comments

Comments
 (0)