Skip to content

Commit

Permalink
Fix a massive performance bug in A* and Dijkstra algorithms (10-100 t…
Browse files Browse the repository at this point in the history
…imes faster now).
  • Loading branch information
renggli committed Dec 17, 2023
1 parent f59f888 commit e8808eb
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lib/src/graph/algorithms/a_star_search.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class _AStarSearchIterator<V> implements Iterator<Path<V, num>> {

final AStarSearchIterable<V> iterable;
final Map<V, _State<V>> states;
final PriorityQueue<_State<V>> todo = PriorityQueue();
final todo = PriorityQueue<_State<V>>();

@override
late Path<V, num> current;
Expand All @@ -61,11 +61,11 @@ class _AStarSearchIterator<V> implements Iterator<Path<V, num>> {
final targetState = states.putIfAbsent(
target, () => _State<V>(vertex: target, total: double.infinity));
if (total < targetState.total) {
if (targetState.total.isFinite) todo.remove(targetState);
targetState.parent = sourceState;
targetState.value = value;
targetState.total = total;
targetState.estimate = total + iterable.costEstimate(target);
todo.remove(targetState);
todo.add(targetState);
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/graph/algorithms/dijkstra_search.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class _DijkstraSearchIterator<V> implements Iterator<Path<V, num>> {

final DijkstraSearchIterable<V> iterable;
final Map<V, _State<V>> states;
final PriorityQueue<_State<V>> todo = PriorityQueue();
final todo = PriorityQueue<_State<V>>();

@override
late Path<V, num> current;
Expand All @@ -56,10 +56,10 @@ class _DijkstraSearchIterator<V> implements Iterator<Path<V, num>> {
final targetState = states.putIfAbsent(
target, () => _State<V>(vertex: target, total: double.infinity));
if (total < targetState.total) {
if (targetState.total.isFinite) todo.remove(targetState);
targetState.parent = sourceState;
targetState.value = value;
targetState.total = total;
todo.remove(targetState);
todo.add(targetState);
}
}
Expand Down

0 comments on commit e8808eb

Please sign in to comment.