Skip to content

Commit

Permalink
src: Add and use default MinPQ.addOrChangePriority
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinlin1 committed Jan 16, 2023
1 parent a20e8e9 commit 56ad2ca
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
6 changes: 1 addition & 5 deletions src/graphs/shortestpaths/AStarSolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,7 @@ public AStarSolver(AStarGraph<V> graph, V start, V goal) {
edgeTo.put(to, e);
distTo.put(to, newDist);
double priority = newDist + graph.estimatedDistance(to, goal);
if (pq.contains(to)) {
pq.changePriority(to, priority);
} else {
pq.add(to, priority);
}
pq.addOrChangePriority(to, priority);
}
}
}
Expand Down
6 changes: 1 addition & 5 deletions src/graphs/shortestpaths/DijkstraSolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@ public DijkstraSolver(Graph<V> graph, V start) {
if (newDist < oldDist) {
edgeTo.put(to, e);
distTo.put(to, newDist);
if (pq.contains(to)) {
pq.changePriority(to, newDist);
} else {
pq.add(to, newDist);
}
pq.addOrChangePriority(to, newDist);
}
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/minpq/MinPQ.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ public interface MinPQ<E> {
*/
void add(E element, double priority);

/**
* Adds an element with the given priority value if it is not already present. Otherwise, updates the priority value
* of the existing element.
*
* @param element the element to add or update.
* @param priority the priority value for the element.
*/
default void addOrChangePriority(E element, double priority) {
if (!contains(element)) {
add(element, priority);
} else {
changePriority(element, priority);
}
}

/**
* Returns true if the given element is in this priority queue.
*
Expand Down

0 comments on commit 56ad2ca

Please sign in to comment.