Skip to content
Snippets Groups Projects
Commit 411af3e6 authored by skhourshed2's avatar skhourshed2
Browse files

implemented solveByAStar and heurisitic functions

parent 81fa6cd9
Branches
No related tags found
No related merge requests found
...@@ -72,7 +72,7 @@ export function solveByDijkstras(maze) { ...@@ -72,7 +72,7 @@ export function solveByDijkstras(maze) {
} }
function heuristic(maze, cell) { function heuristic(maze, cell) {
return 0; // TODO: stub return Math.abs(maze.exit.x - cell.x) + Math.abs(maze.exit.y - cell.y);
} }
export function solveByAStar(maze) { export function solveByAStar(maze) {
...@@ -80,33 +80,28 @@ export function solveByAStar(maze) { ...@@ -80,33 +80,28 @@ export function solveByAStar(maze) {
const worklist = new PriorityQueue(); const worklist = new PriorityQueue();
worklist.insert( worklist.insert(
new Edge(undefined, maze.entrance, 0), new Edge(undefined, maze.entrance, 0),
0 + heuristic(maze.entrance, maze.exit), 0 + heuristic(maze, maze.exit),
); );
while (worklist.size > 0) { while (worklist.size > 0) {
const workitem = worklist.remove(); const workitem = worklist.remove();
if (backpointers.has(workitem.to) && if (backpointers.has(workitem.to)) {
backpointers.get(workitem.to).distance <= workitem.distance) {
continue; continue;
} }
workitem.to.type = CellType.CONSIDERED; workitem.to.type = CellType.CONSIDERED;
backpointers.set(workitem.to, workitem); backpointers.set(workitem.to, workitem);
if (workitem.to === maze.exit) { if (workitem.to === maze.exit) {
const reversedPath = [];
for (let current = maze.exit; for (let current = maze.exit;
current !== undefined; current !== undefined;
current = backpointers.get(current).from) { current = backpointers.get(current).from) {
reversedPath.push(current);
current.type = CellType.SOLUTION; current.type = CellType.SOLUTION;
} }
return reversedPath.reverse(); return;
} }
for (const incidence of workitem.to.neighbors) { for (const neighbor of workitem.to.neighbors) {
worklist.insert( worklist.insert(
new Edge(workitem.to, incidence.destination, workitem.distance), new Edge(workitem.to, neighbor, workitem.distance + 1),
workitem.distance + workitem.distance + 1 + heuristic(maze, neighbor),
heuristic(incidence.destination, maze.exit),
); );
} }
} }
return undefined;
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment