Skip to content

About

An interactive pathfinding visualization tool that showcases the working of the A* (A-Star) algorithm in a grid-based environment. The application enables users to observe how the algorithm efficiently computes the shortest path between a start and end point while dynamically navigating around obstacles.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

A* (A-Star) Algorithm Visualizer

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.

A* Visualizer Screenshot

๐Ÿง  About the A* Algorithm

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.

How A* Works

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

Algorithm Steps

  1. Initialize: Add the start node to the open set with f(start) = h(start)
  2. 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

Heuristic Function

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.

๐Ÿ†š A* vs Dijkstra's Algorithm

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)

Key Differences

  1. Informed vs Uninformed: A* is an informed search algorithm that uses domain knowledge (heuristic), while Dijkstra's is uninformed.

  2. Goal-Directed: A* directs its search toward the goal, making it faster for single-destination pathfinding.

  3. Node Exploration: Dijkstra's explores nodes in all directions equally, while A* prioritizes nodes that appear to be closer to the goal.

  4. Performance: A* typically finds paths faster than Dijkstra's in grid-based pathfinding scenarios.

๐Ÿ› ๏ธ Tech Stack

Frontend Framework

  • 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

Styling & UI

  • 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

Development Tools

  • ESLint 9.9.1: Code linting and quality enforcement
  • TypeScript ESLint: TypeScript-specific linting rules
  • React Hooks ESLint: React hooks best practices enforcement

Build & Development

  • Vite Plugin React: React support for Vite
  • Autoprefixer: Automatic vendor prefix addition

๐Ÿ—๏ธ Project Structure

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

๐Ÿ”„ Project Workflow

1. Grid Initialization

// Create a 20x50 grid with start and finish nodes
const grid = createInitialGrid();
// Start node at (10, 15), Finish node at (10, 35)

2. User Interaction

  • Drawing Mode: Click and drag to create walls
  • Select Mode: Navigate and select nodes
  • Real-time Updates: Grid updates immediately with user interactions

3. Algorithm Execution

// A* algorithm execution flow
const visitedNodes = aStar(grid, startNode, finishNode);
const shortestPath = getNodesInShortestPathOrder(finishNode);

4. Visualization Process

  1. Node Exploration Animation: Visited nodes turn blue with 10ms intervals
  2. Path Reconstruction: Shortest path nodes turn yellow with 50ms intervals
  3. Real-time Feedback: Progress indication and state management

5. State Management

  • Grid State: 2D array of NodeType objects
  • Interaction State: Mouse press states and current mode
  • Animation State: Running status and timing control

๐Ÿš€ Features

Core Functionality

  • 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

User Interface

  • 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

Algorithm Features

  • Optimal Pathfinding: Guaranteed shortest path when using admissible heuristic
  • Obstacle Avoidance: Navigate around user-created walls
  • Performance Optimization: Efficient node exploration with heuristic guidance

๐Ÿ“ฆ Installation & Setup

Prerequisites

  • Node.js (v16 or higher)
  • npm or yarn package manager

Installation Steps

  1. Clone the repository:

    git clone https://github.com/drunktrader/aStar-algorithm.git
    cd aStar-algorithm
  2. Install dependencies:

    npm install
  3. Start development server:

    npm run dev
  4. Open in browser: Navigate to http://localhost:5173

Build for Production

npm run build
npm run preview

๐ŸŽฎ Usage Guide

Basic Operation

  1. Setup: The grid loads with predefined start (green) and finish (red) nodes
  2. Create Obstacles: Switch to "Drawing Mode" and click/drag to create walls
  3. Visualize: Click "Visualize" to run the A* algorithm
  4. Reset: Use "Reset Grid" to clear the visualization and walls

Visual Legend

  • ๐ŸŸข Green: Start node
  • ๐Ÿ”ด Red: Finish/Goal node
  • โฌ› Black: Wall/Obstacle
  • ๐Ÿ”ต Blue: Visited nodes during search
  • ๐ŸŸก Yellow: Optimal path
  • โฌœ White: Unvisited nodes

Advanced Features

  • Interactive Wall Creation: Real-time wall placement and removal
  • Algorithm Animation: Adjustable speed visualization
  • Path Reconstruction: Clear shortest path highlighting

๐Ÿงช Algorithm Implementation Details

Node Structure

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)
}

Core Algorithm Functions

  1. aStar(): Main algorithm implementation
  2. heuristic(): Manhattan distance calculation
  3. getUnvisitedNeighbors(): Adjacent node retrieval
  4. getNodesInShortestPathOrder(): Path reconstruction

๐Ÿค Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Development Guidelines

  • Follow TypeScript best practices
  • Maintain consistent code formatting
  • Add comments for complex algorithm logic
  • Test new features thoroughly

๐Ÿ“„ License

This project is open source and available under the MIT License.

๐Ÿ“ž Contact

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.*

About

An interactive pathfinding visualization tool that showcases the working of the A* (A-Star) algorithm in a grid-based environment. The application enables users to observe how the algorithm efficiently computes the shortest path between a start and end point while dynamically navigating around obstacles.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages