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,167 @@
package com.algorithmrace.visualizer.algorithms.pathfinding;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

public class BidirectionalBFSModel extends PathfindingModel {
private final Queue<GridCell> forwardQueue = new LinkedList<>();
private final Queue<GridCell> backwardQueue = new LinkedList<>();

private final Map<GridCell, GridCell> parentForward = new HashMap<>();
private final Map<GridCell, GridCell> parentBackward = new HashMap<>();

private boolean forwardTurn = true;

public BidirectionalBFSModel() {
super("Bidirectional BFS");
}

@Override
public void step() {
if (isDone()) {
return;
}

if (forwardQueue.isEmpty() && backwardQueue.isEmpty()) {
markDone();
return;
}

if (forwardTurn && !forwardQueue.isEmpty()) {
expandForward();
if (!isDone()) {
forwardTurn = false;
}
} else if (!forwardTurn && !backwardQueue.isEmpty()) {
expandBackward();
if (!isDone()) {
forwardTurn = true;
}
} else if (forwardQueue.isEmpty()) {
expandBackward();
} else {
expandForward();
}
}

private void expandForward() {
GridCell current = forwardQueue.poll();
if (current == null) return;

if (parentBackward.containsKey(current) || current == end) {
reconstructBidirectionalPath(current);
markDone();
return;
}

if (current != start) {
current.state = CellState.VISITED_FORWARD;
}
addStep();

for (GridCell nb : getNeighbors(current)) {
if (nb.state == CellState.EMPTY
|| nb.state == CellState.END
|| nb.state == CellState.FRONTIER_BACKWARD
|| nb.state == CellState.VISITED_BACKWARD) {
if (!parentForward.containsKey(nb)) {
parentForward.put(nb, current);
if (parentBackward.containsKey(nb) || nb == end) {
reconstructBidirectionalPath(nb);
markDone();
return;
}
if (nb.state == CellState.EMPTY) {
nb.state = CellState.FRONTIER_FORWARD;
}
forwardQueue.add(nb);
}
}
}
}

private void expandBackward() {
GridCell current = backwardQueue.poll();
if (current == null) return;

if (parentForward.containsKey(current) || current == start) {
reconstructBidirectionalPath(current);
markDone();
return;
}

if (current != end) {
current.state = CellState.VISITED_BACKWARD;
}
addStep();

for (GridCell nb : getNeighbors(current)) {
if (nb.state == CellState.EMPTY
|| nb.state == CellState.START
|| nb.state == CellState.FRONTIER_FORWARD
|| nb.state == CellState.VISITED_FORWARD) {
if (!parentBackward.containsKey(nb)) {
parentBackward.put(nb, current);
if (parentForward.containsKey(nb) || nb == start) {
reconstructBidirectionalPath(nb);
markDone();
return;
}
if (nb.state == CellState.EMPTY) {
nb.state = CellState.FRONTIER_BACKWARD;
}
backwardQueue.add(nb);
}
}
}
}

private void reconstructBidirectionalPath(GridCell intersection) {
path.clear();

GridCell current = intersection;
while (current != null && current != start) {
path.add(0, current);
current = parentForward.get(current);
}
if (start != null && (path.isEmpty() || path.get(0) != start)) {
path.add(0, start);
}

current = parentBackward.get(intersection);
while (current != null) {
path.add(current);
current = parentBackward.get(current);
}

pathFound = true;
for (GridCell cell : path) {
if (cell != start && cell != end) {
cell.state = CellState.PATH;
}
}
}

@Override
public void reset() {
forwardQueue.clear();
backwardQueue.clear();
parentForward.clear();
parentBackward.clear();
forwardTurn = true;
resetStats();

if (start != null) {
start.gCost = 0;
parentForward.put(start, null);
forwardQueue.add(start);
}
if (end != null) {
end.gCost = 0;
parentBackward.put(end, null);
backwardQueue.add(end);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,9 @@ public enum CellState {
END,
VISITED,
PATH,
FRONTIER
FRONTIER,
VISITED_FORWARD,
VISITED_BACKWARD,
FRONTIER_FORWARD,
FRONTIER_BACKWARD
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ public static PathfindingModel create(String name) {
case "Dijkstra" -> new DijkstraModel();
case "A* Search" -> new AStarModel();
case "Bellman-Ford" -> new BellmanFordModel();
case "Bidirectional BFS" -> new BidirectionalBFSModel();
default ->
throw new IllegalArgumentException("Unrecognized pathfinding algorithm requested.");
};
}

public static List<String> allNames() {
return List.of("BFS", "DFS", "Dijkstra", "A* Search", "Bellman-Ford");
return List.of("BFS", "DFS", "Dijkstra", "A* Search", "Bellman-Ford", "Bidirectional BFS");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public abstract class PathfindingModel {

private final String name;
private boolean done;
private boolean pathFound;
protected boolean pathFound;
private int steps;

protected PathfindingModel(String name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ 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(
"Bidirectional BFS",
"O(b^(d/2))",
"O(b^(d/2))",
"O(b^(d/2))",
"O(b^(d/2))",
"Explores from both start and end, halving the search depth.",
"expand forward\nexpand backward\nstop when frontiers intersect");
add(
"Bellman-Ford",
"O(V*E)",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
class PathfindingAlgorithmsTest {

private final SimulationService simulationService = new SimulationService();
private final List<String> algorithms = List.of("BFS", "DFS", "Dijkstra", "A* Search");
private final List<String> algorithms =
List.of("BFS", "DFS", "Dijkstra", "A* Search", "Bidirectional BFS");

@Test
@DisplayName("Verify pathfinding models find path in unblocked grid")
Expand Down
18 changes: 15 additions & 3 deletions frontend/src/components/PathCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ const stateColor: Record<string, string> = {
END: '#ff0055',
VISITED: '#1e1b4b',
FRONTIER: '#6366f1',
PATH: '#ffd166'
PATH: '#ffd166',
VISITED_FORWARD: '#1e1b4b',
VISITED_BACKWARD: '#4c1d95',
FRONTIER_FORWARD: '#6366f1',
FRONTIER_BACKWARD: '#a855f7'
};

export function PathCanvas({
Expand Down Expand Up @@ -77,6 +81,12 @@ export function PathCanvas({
} else if (state === 'FRONTIER') {
isGlow = true;
glowColor = 'rgba(14, 165, 233, 0.5)';
} else if (state === 'FRONTIER_FORWARD') {
isGlow = true;
glowColor = 'rgba(14, 165, 233, 0.5)';
} else if (state === 'FRONTIER_BACKWARD') {
isGlow = true;
glowColor = 'rgba(168, 85, 247, 0.5)';
}

if (isGlow) {
Expand All @@ -90,8 +100,10 @@ export function PathCanvas({
if (isLight) {
if (state === 'EMPTY') cellColor = '#f2f7ff';
else if (state === 'WALL') cellColor = '#dae2fd';
else if (state === 'VISITED') cellColor = '#c0e8ff';
else if (state === 'FRONTIER') cellColor = '#0ea5e9';
else if (state === 'VISITED' || state === 'VISITED_FORWARD') cellColor = '#c0e8ff';
else if (state === 'VISITED_BACKWARD') cellColor = '#e9d5ff';
else if (state === 'FRONTIER' || state === 'FRONTIER_FORWARD') cellColor = '#0ea5e9';
else if (state === 'FRONTIER_BACKWARD') cellColor = '#a855f7';
}

ctx.fillStyle = cellColor;
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/PerformanceComparison.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export function PerformanceComparison({
for (let r = 0; r < frame.grid.length; r++) {
for (let c = 0; c < frame.grid[r].length; c++) {
const cellState = frame.grid[r][c];
if (cellState === 'VISITED' || cellState === 'PATH') {
if (cellState === 'VISITED' || cellState === 'VISITED_FORWARD' || cellState === 'VISITED_BACKWARD' || cellState === 'PATH') {
nodesVisited++;
} else if (cellState === 'FRONTIER') {
frontierSize++;
Expand Down
8 changes: 8 additions & 0 deletions patch_metadata_fix.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/bash
awk '
BEGIN { count = 0 }
/Bidirectional BFS/ { count++ }
count == 2 && /Bidirectional BFS/ { skip = 8; next }
skip > 0 { skip--; next }
{ print }
' frontend/src/data/algorithmMetadata.ts > tmp && mv tmp frontend/src/data/algorithmMetadata.ts
2 changes: 2 additions & 0 deletions patch_metadata_fix2.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
sed -i "/'Greedy Best-First':/i \ 'Bidirectional BFS': {\n complete: true,\n optimal: true,\n weighted: false,\n bestFor: 'Large unweighted graphs where both endpoints are known',\n advantage: 'Explores ~half the nodes compared to standard BFS',\n limitation: 'Complex implementation; restricted to unweighted graphs',\n }," frontend/src/data/algorithmMetadata.ts
Loading