A comprehensive pathfinding visualization tool that demonstrates the A* (A-Star) algorithm in action. This interactive web application allows users to visualize how the A* algorithm finds the optimal path between two points while navigating around obstacles in a grid-based environment.
The A* (pronounced "A-star") algorithm is a graph traversal and path search algorithm that is used in pathfinding and graph traversal. It was first described by Peter Hart, Nils Nilsson, and Bertram Raphael in 1968.
A* uses a heuristic function to guide its search, making it more efficient than uninformed search algorithms like Dijkstra's algorithm. The algorithm maintains three key values for each node:
- g(n): The actual cost from the start node to node n
- h(n): The heuristic estimate of the cost from node n to the goal
- f(n) = g(n) + h(n): The total estimated cost of the path through node n
- Initialize: Add the start node to the open set with f(start) = h(start)
- Loop: While the open set is not empty:
- Select the node with the lowest f(n) value from the open set
- If this node is the goal, reconstruct and return the path
- Move the current node from open set to closed set
- For each neighbor of the current node:
- Skip if the neighbor is in the closed set or is a wall
- Calculate tentative g score
- If neighbor is not in open set or new g score is better:
- Update the neighbor's g, h, and f values
- Set the neighbor's parent to current node
- Add neighbor to open set if not already there
This implementation uses the Manhattan Distance heuristic:
h(n) = |current.x - goal.x| + |current.y - goal.y|
This heuristic is admissible (never overestimates the actual cost) and consistent, ensuring that A* finds the optimal path.
| Aspect | A* Algorithm | Dijkstra's Algorithm |
|---|---|---|
| Search Strategy | Best-first search with heuristic | Uniform-cost search |
| Heuristic | Uses heuristic function h(n) | No heuristic (h(n) = 0) |
| Efficiency | More efficient, explores fewer nodes | Less efficient, explores more nodes |
| Optimality | Optimal if heuristic is admissible | Always optimal |
| Use Case | When you know the goal location | When exploring all possible paths |
| Time Complexity | O(b^d) but typically much faster | O((V + E) log V) |
| Space Complexity | O(b^d) | O(V) |
-
Informed vs Uninformed: A* is an informed search algorithm that uses domain knowledge (heuristic), while Dijkstra's is uninformed.
-
Goal-Directed: A* directs its search toward the goal, making it faster for single-destination pathfinding.
-
Node Exploration: Dijkstra's explores nodes in all directions equally, while A* prioritizes nodes that appear to be closer to the goal.
-
Performance: A* typically finds paths faster than Dijkstra's in grid-based pathfinding scenarios.
- React 18.3.1: Modern React with hooks for state management and component lifecycle
- TypeScript 5.5.3: Type-safe development with enhanced IDE support
- Vite 5.4.2: Fast build tool and development server
- Tailwind CSS 3.4.1: Utility-first CSS framework for rapid UI development
- Lucide React 0.344.0: Beautiful SVG icons for UI elements
- PostCSS 8.4.35: CSS processing with autoprefixer
- ESLint 9.9.1: Code linting and quality enforcement
- TypeScript ESLint: TypeScript-specific linting rules
- React Hooks ESLint: React hooks best practices enforcement
- Vite Plugin React: React support for Vite
- Autoprefixer: Automatic vendor prefix addition
aStar-algorithm/
โโโ src/
โ โโโ components/
โ โ โโโ Grid.tsx # Main grid component
โ โ โโโ Node.tsx # Individual node component
โ โโโ algorithms/
โ โ โโโ aStar.ts # A* algorithm implementation
โ โโโ types.ts # TypeScript type definitions
โ โโโ App.tsx # Main application component
โ โโโ main.tsx # Application entry point
โ โโโ index.css # Global styles
โโโ public/ # Static assets
โโโ index.html # HTML template
โโโ package.json # Dependencies and scripts
โโโ tailwind.config.js # Tailwind configuration
โโโ tsconfig.json # TypeScript configuration
โโโ vite.config.ts # Vite configuration
// Create a 20x50 grid with start and finish nodes
const grid = createInitialGrid();
// Start node at (10, 15), Finish node at (10, 35)- Drawing Mode: Click and drag to create walls
- Select Mode: Navigate and select nodes
- Real-time Updates: Grid updates immediately with user interactions
// A* algorithm execution flow
const visitedNodes = aStar(grid, startNode, finishNode);
const shortestPath = getNodesInShortestPathOrder(finishNode);- Node Exploration Animation: Visited nodes turn blue with 10ms intervals
- Path Reconstruction: Shortest path nodes turn yellow with 50ms intervals
- Real-time Feedback: Progress indication and state management
- Grid State: 2D array of NodeType objects
- Interaction State: Mouse press states and current mode
- Animation State: Running status and timing control
- Interactive Grid: 20x50 customizable grid system
- Wall Creation: Click and drag to create obstacles
- Real-time Visualization: Step-by-step algorithm execution
- Path Highlighting: Clear visualization of the optimal path
- Mode Switching: Toggle between select and drawing modes
- Visual Feedback: Color-coded nodes for different states
- Control Panel: Play, reset, and mode selection buttons
- Responsive Design: Works on different screen sizes
- Optimal Pathfinding: Guaranteed shortest path when using admissible heuristic
- Obstacle Avoidance: Navigate around user-created walls
- Performance Optimization: Efficient node exploration with heuristic guidance
- Node.js (v16 or higher)
- npm or yarn package manager
-
Clone the repository:
git clone https://github.com/drunktrader/aStar-algorithm.git cd aStar-algorithm -
Install dependencies:
npm install
-
Start development server:
npm run dev
-
Open in browser: Navigate to
http://localhost:5173
npm run build
npm run preview- Setup: The grid loads with predefined start (green) and finish (red) nodes
- Create Obstacles: Switch to "Drawing Mode" and click/drag to create walls
- Visualize: Click "Visualize" to run the A* algorithm
- Reset: Use "Reset Grid" to clear the visualization and walls
- ๐ข Green: Start node
- ๐ด Red: Finish/Goal node
- โฌ Black: Wall/Obstacle
- ๐ต Blue: Visited nodes during search
- ๐ก Yellow: Optimal path
- โฌ White: Unvisited nodes
- Interactive Wall Creation: Real-time wall placement and removal
- Algorithm Animation: Adjustable speed visualization
- Path Reconstruction: Clear shortest path highlighting
interface NodeType {
row: number; // Grid position
col: number; // Grid position
isStart: boolean; // Start node flag
isFinish: boolean; // Goal node flag
isWall: boolean; // Obstacle flag
isVisited: boolean; // Exploration status
isPath: boolean; // Final path flag
distance: number; // Legacy for compatibility
previousNode: NodeType | null; // Parent node for path reconstruction
g: number; // Actual cost from start
h: number; // Heuristic cost to goal
f: number; // Total cost (g + h)
}- aStar(): Main algorithm implementation
- heuristic(): Manhattan distance calculation
- getUnvisitedNeighbors(): Adjacent node retrieval
- getNodesInShortestPathOrder(): Path reconstruction
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
- Follow TypeScript best practices
- Maintain consistent code formatting
- Add comments for complex algorithm logic
- Test new features thoroughly
This project is open source and available under the MIT License.
For questions, suggestions, or contributions, please open an issue on GitHub or reach out to the project maintainers.
This project demonstrates the power and efficiency of the A algorithm in pathfinding applications, providing an educational and interactive way to understand one of computer science's most important algorithms.*
