Created
January 1, 2024 23:36
-
-
Save adamstirtan/3f888ac3931c066d611fd0131ab2c542 to your computer and use it in GitHub Desktop.
A* Algorithm in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // A* pathfinding algorithm | |
| function astar(start, end) { | |
| const openSet = []; | |
| const closedSet = []; | |
| openSet.push(start); | |
| while (openSet.length > 0) { | |
| let currentNode = openSet[0]; | |
| // Find the node with the lowest total cost in the open set | |
| for (let i = 1; i < openSet.length; i++) { | |
| if (openSet[i].f < currentNode.f || (openSet[i].f === currentNode.f && openSet[i].h < currentNode.h)) { | |
| currentNode = openSet[i]; | |
| } | |
| } | |
| openSet.splice(openSet.indexOf(currentNode), 1); | |
| closedSet.push(currentNode); | |
| if (currentNode.row === end.row && currentNode.col === end.col) { | |
| // Reconstruct the path if the goal is reached | |
| let path = []; | |
| let temp = currentNode; | |
| while (temp) { | |
| path.push(temp); | |
| temp = temp.parent; | |
| } | |
| return path.reverse(); | |
| } | |
| const neighbors = []; | |
| const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; | |
| for (let dir of directions) { | |
| const neighborRow = currentNode.row + dir[0]; | |
| const neighborCol = currentNode.col + dir[1]; | |
| if (isValidCell(neighborRow, neighborCol)) { | |
| const neighbor = { | |
| row: neighborRow, | |
| col: neighborCol, | |
| g: currentNode.g + 1, | |
| h: heuristic({ row: neighborRow, col: neighborCol }, end), | |
| f: 0, | |
| parent: currentNode, | |
| }; | |
| neighbor.f = neighbor.g + neighbor.h; | |
| if (closedSet.some((node) => node.row === neighbor.row && node.col === neighbor.col)) { | |
| continue; | |
| } | |
| const openSetNode = openSet.find((node) => node.row === neighbor.row && node.col === neighbor.col); | |
| if (!openSetNode || neighbor.g < openSetNode.g) { | |
| openSet.push(neighbor); | |
| } | |
| } | |
| } | |
| } | |
| // No path found | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment