Algorithms · interactive · step by step

Pathfinding Visualizer

Draw walls and weights on a grid, or generate a maze, and watch BFS, DFS, Dijkstra, A* and greedy best-first search find their way from start to target, cell by cell, with the frontier and the final path.

Draw

Explored 0Path —Cost —start target wall weight ×5 frontier explored path

Step 0Space play · ←→ step

Board:

Reference

Pathfinding algorithms compared

AlgorithmUses weightsShortest pathData structureTime
BFSNoYes (fewest steps)QueueO(V + E)
DFSNoNoStackO(V + E)
DijkstraYesYesPriority queueO((V + E) log V)
A*YesYes (with an admissible h)Priority queueO((V + E) log V), usually far less
Greedy best-firstYesNoPriority queueO((V + E) log V)

Code

A* and BFS on a grid

Python (A*)
import heapq

def astar(grid, start, goal):
    """grid[r][c]: 0 = open, 1 = wall. start/goal: (row, col)."""
    def h(p): return abs(p[0] - goal[0]) + abs(p[1] - goal[1])
    g = {start: 0}
    parent = {start: None}
    queue = [(h(start), start)]
    while queue:
        _, cell = heapq.heappop(queue)
        if cell == goal:
            path = []
            while cell:
                path.append(cell)
                cell = parent[cell]
            return path[::-1]
        r, c = cell
        for n in ((r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)):
            if 0 <= n[0] < len(grid) and 0 <= n[1] < len(grid[0]) and not grid[n[0]][n[1]]:
                cost = g[cell] + 1
                if cost < g.get(n, float("inf")):
                    g[n], parent[n] = cost, cell
                    heapq.heappush(queue, (cost + h(n), n))
    return None  # no path
Copy and step through it in Compilers
JavaScript (BFS)
function bfs(grid, start, goal) {
  // grid[r][c]: 0 = open, 1 = wall. start/goal: [row, col].
  const key = ([r, c]) => r + ',' + c;
  const parent = new Map([[key(start), null]]);
  const queue = [start];
  while (queue.length) {
    const cell = queue.shift();
    if (key(cell) === key(goal)) {
      const path = [];
      for (let k = key(cell); k; k = parent.get(k)) path.unshift(k);
      return path;
    }
    const [r, c] = cell;
    for (const n of [[r - 1, c], [r, c + 1], [r + 1, c], [r, c - 1]]) {
      if (grid[n[0]]?.[n[1]] === 0 && !parent.has(key(n))) {
        parent.set(key(n), key(cell));
        queue.push(n);
      }
    }
  }
  return null; // no path
}
Copy and step through it in Compilers

Questions

Pathfinding Visualizer FAQ

Free, private and works offline: everything runs in your browser.

Which pathfinding algorithm is best?

For a map where every step costs the same, A* is usually best: it finds the shortest path while exploring far fewer cells. On an empty 21×41 grid, A* explored 29 cells to cross 28 steps, BFS 615 and Dijkstra 605. Use Dijkstra when there is no good estimate of the distance left, and BFS when edges have no weights.

What is the difference between BFS and DFS?

BFS explores in rings: everything 1 step away, then 2, and so on, so the first time it reaches the target it has the fewest-steps path. DFS dives down one route until it hits a dead end, then backtracks, so it finds a path but often a long one. In a maze generated here, both found the 168-step route (a perfect maze has only one), but BFS explored 321 cells and DFS 313.

How does A* work?

A* ranks each cell by f = g + h: g is the cost from the start so far, and h is a guess of the cost still to go (here the Manhattan distance, rows plus columns). As long as h never overestimates, A* still finds the cheapest path, and it heads towards the target instead of spreading out evenly like Dijkstra.

What do the weights do?

A weight cell costs 5 to enter instead of 1, like mud or traffic. Dijkstra and A* go around weights when that is cheaper. BFS and DFS ignore weights, so on a weighted grid their path may not be the cheapest.

Why is greedy best-first search fast but not always right?

It only looks at the estimated distance to the target and ignores how far it has already come, so it races towards the goal. Around walls it can commit to a long detour. Draw a U-shaped wall between start and target to see it.

How do I use the grid?

Drag the green start or red target to move them. Click or drag on empty cells to draw walls (or weights, with “Draw: weights” selected), and on walls to erase. Then press Visualize. Every step can be replayed, paused or stepped through.

Built and maintained by Zubaer Ahammed · Updated · Runs on your device; nothing you add is uploaded