Skip to content

Commit 56ad2ca

Browse files
committed
src: Add and use default MinPQ.addOrChangePriority
1 parent a20e8e9 commit 56ad2ca

File tree

3 files changed

+17
-10
lines changed

3 files changed

+17
-10
lines changed

src/graphs/shortestpaths/AStarSolver.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,7 @@ public AStarSolver(AStarGraph<V> graph, V start, V goal) {
4343
edgeTo.put(to, e);
4444
distTo.put(to, newDist);
4545
double priority = newDist + graph.estimatedDistance(to, goal);
46-
if (pq.contains(to)) {
47-
pq.changePriority(to, priority);
48-
} else {
49-
pq.add(to, priority);
50-
}
46+
pq.addOrChangePriority(to, priority);
5147
}
5248
}
5349
}

src/graphs/shortestpaths/DijkstraSolver.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,7 @@ public DijkstraSolver(Graph<V> graph, V start) {
3939
if (newDist < oldDist) {
4040
edgeTo.put(to, e);
4141
distTo.put(to, newDist);
42-
if (pq.contains(to)) {
43-
pq.changePriority(to, newDist);
44-
} else {
45-
pq.add(to, newDist);
46-
}
42+
pq.addOrChangePriority(to, newDist);
4743
}
4844
}
4945
}

src/minpq/MinPQ.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,21 @@ public interface MinPQ<E> {
2222
*/
2323
void add(E element, double priority);
2424

25+
/**
26+
* Adds an element with the given priority value if it is not already present. Otherwise, updates the priority value
27+
* of the existing element.
28+
*
29+
* @param element the element to add or update.
30+
* @param priority the priority value for the element.
31+
*/
32+
default void addOrChangePriority(E element, double priority) {
33+
if (!contains(element)) {
34+
add(element, priority);
35+
} else {
36+
changePriority(element, priority);
37+
}
38+
}
39+
2540
/**
2641
* Returns true if the given element is in this priority queue.
2742
*

0 commit comments

Comments
 (0)