This project implements a visual representation of the A* Pathfinding algorithm using React and TypeScript. It allows users to customize the grid, set start and end nodes, add walls, and visualize the shortest path calculated by the algorithm.
- Customizable Grid: Adjust the grid dimensions and tile states.
- Start/End Nodes: Click to set the start and end positions for the pathfinding.
- Walls: Add or remove wall tiles to block the path.
- Diagonal Movement: Toggle diagonal movement in the algorithm.
- Heuristic Choices: Switch between Manhattan and Diagonal distance for heuristic calculation.
- Random Maze Generation: Generate random mazes using Prim's algorithm.
The algorithm supports two heuristics to estimate the shortest path:
- Used when diagonal movement is disabled.
- Formula:
D * (dx + dy)Dis the cost of moving in a straight line.dxanddyare the horizontal and vertical distances, respectively.
- Suitable for grids where movement is restricted to straight lines (up, down, left, right).
- Used when diagonal movement is enabled.
- Formula:
D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)Dis the cost of straight-line movement.D2is the cost of diagonal movement (usually greater thanD).dxanddyare the horizontal and vertical distances, respectively.min(dx, dy)ensures diagonal movement is factored properly.
- Suitable for grids where diagonal movement is allowed, providing a more realistic path.
Here:
Dis the cost of moving in a straight line.D2is the cost of moving diagonally (typically slightly higher thanD).
The A* algorithm finds the shortest path by:
- Initializing the open set with the start node.
- Iteratively selecting the node with the smallest
fCost(wherefCost = gCost + hCost). - Evaluating neighboring nodes:
- Adding valid neighbors to the open set.
- Updating costs (
gCostandhCost) and parent nodes as needed.
- Terminating when the end node is reached or the open set is empty.
- Backtracking from the end node to reconstruct the path.
Key methods in the implementation:
getValidNeighbors: Filters neighbors based on grid boundaries, wall presence, and closed nodes.getManhattanDistanceandgetDiagonalDistance: Calculate heuristic values for the respective movement modes.startPathFind: Main function that drives the A* algorithm, updates state for rendering, and visualizes the process.
To test the A* Pathfinding Visualizer, follow these steps:
- Ensure you have Node.js installed.
- Install dependencies using
npm install.
-
Start the development server with:
npm run dev
-
Visit (http://localhost:3000/) to view and test out the project.