Skip to content

Commit

Permalink
Add BFS solving algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
imericxu committed Jul 10, 2024
1 parent 4e8d3fb commit 03efb6e
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"test": "vitest"
},
"dependencies": {
"@datastructures-js/deque": "^1.0.4",
"async-mutex": "^0.5.0",
"immer": "^10.1.1",
"next": "14.2.4",
Expand Down
41 changes: 41 additions & 0 deletions src/lib/algorithms/solving/BFS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { MazeCell } from "@/lib/MazeCell";
import { MazeSolver } from "./MazeSolver";
import { Deque } from "@datastructures-js/deque";
import { buildPath } from "./pathUtils";

export class BFS extends MazeSolver {
private queue = new Deque<MazeCell>();
private cameFrom = new Map<MazeCell, MazeCell>();

protected _step(): [boolean, Readonly<MazeCell>[]] {
const changes: MazeCell[] = [];

// Go through one queue level
const queueSize = this.queue.size();
for (let i = 0; i < queueSize; ++i) {
const current = this.queue.popFront();

if (current === this.end) {
this._path = buildPath(this.cameFrom, this.end);
return [true, []];
}

for (const neighbor of current.connections) {
if (neighbor.state === "solid") {
neighbor.state = "partial";
this.queue.pushBack(neighbor);
this.cameFrom.set(neighbor, current);
changes.push(neighbor);
}
}
}

return [this.queue.isEmpty(), changes];
}

protected initialize(): Readonly<MazeCell>[] {
this.start.state = "partial";
this.queue.pushBack(this.start);
return [this.start];
}
}
14 changes: 14 additions & 0 deletions src/lib/algorithms/solving/pathUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MazeCell } from "@/lib/MazeCell";

export function buildPath(
cameFrom: Map<MazeCell, MazeCell>,
end: MazeCell,
): MazeCell[] {
const path: MazeCell[] = [];
let current: MazeCell | null = end;
while (current !== null) {
path.unshift(current);
current = cameFrom.get(current) ?? null;
}
return path.toReversed();
}

0 comments on commit 03efb6e

Please sign in to comment.