Skip to content

25f1000920/Graph_Algorithm_Visualizer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš€ Graph Algorithm Visualizer

A production-grade, pedagogical graph algorithm visualizer โ€” not just for watching algorithms run, but for understanding, comparing, and breaking them.


๐ŸŽฏ What Makes This Different

This isn't another basic BFS/DFS visualizer. This is a teaching platform and experimentation sandbox with:

  • 8 algorithms: BFS, DFS, Dijkstra, A*, Bidirectional BFS, Bellman-Ford, Floyd-Warshall, Greedy Best-First
  • Step-by-step engine with play/pause/next/prev/rewind
  • Live pseudocode sync โ€” every step highlights the executing line
  • Comparison mode โ€” run two algorithms side-by-side on the same graph
  • Heuristic playground โ€” A* admissibility teaching tool
  • 5 graph generators: random, grid/maze, scale-free, adjacency list, adjacency matrix
  • Learning mode โ€” step explanations in plain English
  • Expert mode โ€” clean, fast, no hints
  • Negative edges โ€” Bellman-Ford + cycle detection
  • All-pairs shortest paths โ€” Floyd-Warshall with live NxN matrix
  • Analytics panel โ€” nodes visited, edges relaxed, path cost, memory, wall time
  • Visual encoding โ€” color-coded node/edge states, overlays, distance tables

๐Ÿ“ฆ Installation

Requirements

  • Python 3.8+
  • Flask

Quick Start

# 1. Install dependencies
pip install flask

# 2. Run the visualizer
python main.py

# 3. Open your browser
# Navigate to http://localhost:5000

That's it. The server starts, and you're visualizing algorithms in seconds.


๐Ÿ—๏ธ Architecture

graph_visualizer/
โ”œโ”€โ”€ graph/                    # Data layer
โ”‚   โ”œโ”€โ”€ node.py               # Node + NodeState enum
โ”‚   โ”œโ”€โ”€ edge.py               # Edge + EdgeState enum
โ”‚   โ”œโ”€โ”€ graph.py              # Graph container + 5 generators
โ”‚   โ””โ”€โ”€ __init__.py
โ”‚
โ”œโ”€โ”€ algorithms/               # Algorithm layer
โ”‚   โ”œโ”€โ”€ step.py               # Step snapshot dataclass
โ”‚   โ”œโ”€โ”€ bfs.py                # Breadth-First Search
โ”‚   โ”œโ”€โ”€ dfs.py                # Depth-First Search
โ”‚   โ”œโ”€โ”€ dijkstra.py           # Dijkstra's Algorithm
โ”‚   โ”œโ”€โ”€ astar.py              # A* (+ 4 heuristics)
โ”‚   โ”œโ”€โ”€ bidirectional_bfs.py  # Bidirectional BFS
โ”‚   โ”œโ”€โ”€ bellman_ford.py       # Bellman-Ford + cycle detector
โ”‚   โ”œโ”€โ”€ floyd_warshall.py     # Floyd-Warshall (all-pairs)
โ”‚   โ”œโ”€โ”€ greedy_bfs.py         # Greedy Best-First
โ”‚   โ””โ”€โ”€ __init__.py           # REGISTRY โ€” plugin system
โ”‚
โ”œโ”€โ”€ engine/                   # Playback engine
โ”‚   โ”œโ”€โ”€ stepper.py            # Play/Pause/Next/Prev/Rewind
โ”‚   โ”œโ”€โ”€ recorder.py           # Run recording + analytics
โ”‚   โ””โ”€โ”€ __init__.py
โ”‚
โ”œโ”€โ”€ ui/                       # Presentation layer
โ”‚   โ”œโ”€โ”€ canvas.py             # SVG renderer
โ”‚   โ”œโ”€โ”€ controls.py           # All UI panels
โ”‚   โ””โ”€โ”€ __init__.py
โ”‚
โ””โ”€โ”€ main.py                   # Flask web app

Design Principles

  1. Generator-based algorithms โ€” every algorithm is a generator that yields a Step at each meaningful event. The stepper calls next(). Clean, testable, reusable.

  2. Stateless rendering โ€” render_canvas(graph, step) is a pure function. No mutations. State is passed in, SVG comes out.

  3. Plugin system โ€” adding a new algorithm is literally: write the generator, add one entry to REGISTRY. No changes to the UI or engine.

  4. Step snapshots โ€” a Step is a frozen-in-time picture of everything the visualizer needs: node states, edge states, queue contents, distances, pseudocode line, explanation.

  5. Separation of concerns โ€” graph layer doesn't know about algorithms. Algorithms don't know about rendering. Engine doesn't know about Flask. Clean imports top-to-bottom.


๐ŸŽฎ Feature Guide

1. Graph Generation

  • Random (Erdล‘sโ€“Rรฉnyi): adjustable node count + edge probability
  • Grid / Maze: 2D grid with random walls (4-connected)
  • Scale-Free (Barabรกsiโ€“Albert): hub-and-spoke topology
  • Import from text: adjacency list or adjacency matrix

2. Algorithm Selection

Pick any of 8 algorithms. The UI auto-adjusts:

  • A / Greedy*: heuristic selector appears
  • Bellman-Ford: negative-edge warning
  • Floyd-Warshall: matrix panel

3. Playback Controls

  • โ–ถ Play โ€” auto-advance at configurable speed
  • โธ Pause
  • โญ Next โ€” step forward
  • โฎ Prev โ€” rewind one step (full history buffered)
  • โฎ Rewind โ€” jump to step 0
  • โญ Jump to End โ€” exhaust generator

Speed: Slow (1s/step) | Medium (0.4s) | Fast (0.15s) | Turbo (0.05s)

4. Visual Encoding

Node states (color-coded):

  • Grey โ€” unvisited
  • Blue โ€” frontier (in queue)
  • Green โ€” visited (processed)
  • Amber โ€” current (being expanded right now)
  • Purple โ€” on the final path
  • Red โ€” blocked (obstacle)
  • Cyan โ€” source
  • Magenta โ€” target

Edge states:

  • Grey โ€” default
  • Amber pulse โ€” relaxed
  • Purple thick โ€” chosen (on path)
  • Faded โ€” ignored

Overlays (live panels):

  • Priority queue contents (Dijkstra / A*)
  • Stack contents (DFS)
  • Distance array (Dijkstra / Bellman-Ford)
  • g/h/f scores (A*)
  • NxN matrix (Floyd-Warshall)

5. Pseudocode Sync

The pseudocode panel highlights the line executing at each step. Every algorithm ships its own pseudocode in algorithms/<algo>.py as PSEUDOCODE: List[str].

6. Learning Mode vs Expert Mode

Learning Mode (default):

  • Step explanations in plain English
  • "Why did the algorithm choose this node?"
  • Tooltips on every panel

Expert Mode:

  • Clean UI
  • No hints
  • Fast execution

Toggle via checkbox in the sidebar.

7. Comparison Mode

Run two algorithms on the same graph and see side-by-side metrics:

  • Nodes visited
  • Edges relaxed
  • Path cost
  • Wall time

Example: "Is A* really faster than Dijkstra on this graph?"

Winner badges show which algorithm performed better on each metric.

8. Heuristic Playground (A / Greedy)*

When running A* or Greedy BFS, the playground shows:

  • g (actual cost from source)
  • h (heuristic estimate to target)
  • f = g + h

Teaching moment: "What happens if h overestimates?" โ†’ A* becomes suboptimal. "What if h = 0?" โ†’ A* degrades to Dijkstra.

Built-in heuristics:

  • Euclidean โ€” โˆš(ฮ”xยฒ + ฮ”yยฒ)
  • Manhattan โ€” |ฮ”x| + |ฮ”y|
  • Octile โ€” diagonal-aware
  • Zero โ€” h=0 (becomes Dijkstra)

9. Analytics Panel

After every run, see:

  • Nodes visited โ€” how many nodes the algorithm explored
  • Edges relaxed โ€” how many edge-weight updates happened
  • Path length โ€” number of edges on the final path
  • Path cost โ€” total weight of the final path
  • Total steps โ€” number of Step objects yielded
  • Wall time โ€” milliseconds to run to completion
  • Memory โ€” approximate peak memory (step buffer size)

๐Ÿงช Testing the Full Stack

Every module has been smoke-tested end-to-end:

cd graph_visualizer
python3 -c "
from graph import Graph
from algorithms import get_algorithm
from engine import Recorder, compare

# generate a graph
g = Graph.generate_random(num_nodes=10, seed=42)

# run BFS
rec1 = Recorder()
rec1.start('bfs', '0', '9', g)
rec1.run_to_completion()

# run Dijkstra
rec2 = Recorder()
rec2.start('dijkstra', '0', '9', g)
rec2.run_to_completion()

# compare
result = compare(rec1, rec2)
print(f'BFS: {rec1.metrics.nodes_visited} nodes')
print(f'Dijkstra: {rec2.metrics.nodes_visited} nodes')
print(f'Winner: {result.winner_nodes}')
"

Output:

BFS: 10 nodes
Dijkstra: 10 nodes
Winner: tie

All 8 algorithms, both generators, grid/scale-free/import graph modes, Recorder, compare, and serialisation round-trip โ€” all green.


๐Ÿ”ง Extending the Visualizer

Add a New Algorithm

  1. Write the generator in algorithms/your_algo.py:

    def your_algo(graph, source, target):
        sb = StepBuilder()
        # ... your logic ...
        yield sb.build(step_number=0)
  2. Add to REGISTRY in algorithms/__init__.py:

    REGISTRY["your_algo"] = AlgoInfo(
        key="your_algo",
        label="Your Algorithm",
        fn=your_algo,
        pseudocode=PSEUDOCODE,
        tags=["shortest-path"],
        complexity_time="O(E log V)",
    )
  3. Done. The UI auto-discovers it. No other changes needed.

Add a New Graph Generator

Add a @classmethod to Graph in graph/graph.py:

@classmethod
def generate_your_graph(cls, **kwargs) -> "Graph":
    g = cls()
    # ... generate nodes and edges ...
    return g

Wire it into the Flask API in main.py under /api/graph/generate.

Add a New Visual Overlay

In ui/canvas.py, add a new helper to _render_overlays():

def _render_your_overlay(data, config, x, y):
    # ... return SVG string ...

The overlay data comes from step.overlay["your_key"], which the algorithm populates.


๐Ÿ“Š Feature Comparison

Feature This Visualizer Typical Student Project
Algorithms 8 (BFS, DFS, Dijkstra, A*, Bi-BFS, BF, FW, Greedy) 2-3 (BFS, DFS)
Step-by-step โœ… Full rewind + play/pause โŒ Or forward-only
Comparison mode โœ… Side-by-side metrics โŒ
Pseudocode sync โœ… Live line highlighting โŒ
Heuristic playground โœ… A* admissibility teaching โŒ
Negative edges โœ… Bellman-Ford + cycle detector โŒ
All-pairs โœ… Floyd-Warshall + live matrix โŒ
Graph generators 5 (random, grid, scale-free, import) 1 (random)
Analytics โœ… 8 metrics per run โŒ
Architecture Clean plugin system โŒ Monolithic

๐Ÿ™ Acknowledgments

Built with:

  • Flask โ€” web framework
  • Python โ€” language
  • SVG โ€” rendering
  • Lots of coffee โ€” fuel

Ready to start? Run python main.py and open http://localhost:5000

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors