Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.algorithmrace.visualizer.algorithms.pathfinding;

import java.util.Comparator;
import java.util.PriorityQueue;

public class GreedyBFSModel extends PathfindingModel {
private final PriorityQueue<GridCell> openSet =
new PriorityQueue<>(Comparator.comparingDouble(c -> c.hCost));

public GreedyBFSModel() {
super("Greedy Best-First");
}

private double heuristic(GridCell a, GridCell b) {
return Math.abs(a.row - b.row) + Math.abs(a.col - b.col);
}

@Override
public void step() {
if (isDone() || openSet.isEmpty()) {
markDone();
return;
}
GridCell current = openSet.poll();
if (current == end) {
reconstructPath(end);
markDone();
return;
}
if (current.state != CellState.START) {
current.state = CellState.VISITED;
}
addStep();
for (GridCell nb : getNeighbors(current)) {
if (nb.state == CellState.EMPTY || nb.state == CellState.END) {
nb.hCost = heuristic(nb, end);
nb.parent = current;
if (nb.state == CellState.EMPTY) {
nb.state = CellState.FRONTIER;
}
openSet.add(nb);
}
}
}

@Override
public void reset() {
openSet.clear();
resetStats();
if (start != null) {
start.hCost = heuristic(start, end);
openSet.add(start);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,20 @@ public static PathfindingModel create(String name) {
case "A* Search" -> new AStarModel();
case "Bellman-Ford" -> new BellmanFordModel();
case "Bidirectional BFS" -> new BidirectionalBFSModel();
case "Greedy Best-First" -> new GreedyBFSModel();
default ->
throw new IllegalArgumentException("Unrecognized pathfinding algorithm requested.");
};
}

public static List<String> allNames() {
return List.of("BFS", "DFS", "Dijkstra", "A* Search", "Bellman-Ford", "Bidirectional BFS");
return List.of(
"BFS",
"DFS",
"Dijkstra",
"A* Search",
"Bellman-Ford",
"Greedy Best-First",
"Bidirectional BFS");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,15 @@ public final class ComplexityCatalog {
"Combines travelled distance with a heuristic estimate to guide the search toward the"
+ " goal.",
"choose lowest f = g + h\nrelax neighbors");
add(
"Greedy Best-First",
"O(b^m)",
"O(b^m)",
"O(b^m)",
"O(b^m)",
"Relies solely on a heuristic distance to the goal, providing a fast but non-optimal"
+ " search.",
"choose lowest h\nrelax neighbors");
add(
"Bidirectional BFS",
"O(b^(d/2))",
Expand Down
Loading