intermediategeneral

Dijkstra and A* Search

Dijkstra and A* Search

When graph edges have different weights (costs), BFS no longer finds the cheapest path — it finds the path with fewest hops. Dijkstra's algorithm and A* both solve the weighted shortest-path problem, but with different strategies.

Dijkstra's Algorithm

Dijkstra explores nodes in order of their total cost from the start. It always expands the cheapest unvisited node next, guaranteeing that when it reaches any node, it has found the cheapest path to it.

Think of it like water flowing through pipes of different widths — it fills the cheapest paths first.

Key Properties

  • Finds the cheapest path (minimum total edge weight)
  • Explores uniformly in all directions by cost
  • Does not use any information about where the goal is
  • Requires non-negative edge weights

A* improves on Dijkstra by adding a heuristic — an estimate of remaining cost to the goal. It prioritizes nodes where actual cost so far + estimated cost to goal is lowest.

The formula: f(node) = g(node) + h(node)

  • g(node) = actual cost from start to this node
  • h(node) = estimated cost from this node to the goal
  • f(node) = total estimated cost of the path through this node

Key Properties

  • Finds the cheapest path (same guarantee as Dijkstra) when the heuristic is admissible
  • Explores fewer nodes than Dijkstra because it's guided toward the goal
  • An admissible heuristic never overestimates the true cost
  • Manhattan distance is admissible for grid-based movement

Graph Setup

Both algorithms use the same weighted graph structure:

class WeightedGraph:
    def __init__(self, num_nodes: int):
        self.num_nodes = num_nodes
        self.edges = [[] for _ in range(num_nodes)]

    def add_edge(self, from_node: int, to_node: int, weight: int):
        self.edges[from_node].append((to_node, weight))
        self.edges[to_node].append((from_node, weight))

    def get_neighbors(self, node: int) -> list[tuple[int, int]]:
        """Returns list of (neighbor, weight) pairs."""
        return self.edges[node]

Code Snippet — Dijkstra

def dijkstra(graph: WeightedGraph, start_node: int, goal_node: int) -> list[int]:
    """Find cheapest path from start to goal using uniform-cost expansion."""
    num_nodes = graph.num_nodes
    cost_to_reach = [float('inf')] * num_nodes
    parent_of = [-1] * num_nodes
    visited = [False] * num_nodes

    cost_to_reach[start_node] = 0

    # Simple priority queue: list of (cost, node), pick minimum each step
    frontier = [(0, start_node)]

    while frontier:
        # Find the unvisited node with lowest cost
        frontier.sort()
        current_cost, current_node = frontier.pop(0)

        if visited[current_node]:
            continue
        visited[current_node] = True

        if current_node == goal_node:
            break

        for neighbor, edge_weight in graph.get_neighbors(current_node):
            if visited[neighbor]:
                continue
            new_cost = current_cost + edge_weight
            if new_cost < cost_to_reach[neighbor]:
                cost_to_reach[neighbor] = new_cost
                parent_of[neighbor] = current_node
                frontier.append((new_cost, neighbor))

    # Reconstruct path
    path = []
    node = goal_node
    while node != -1:
        path.append(node)
        node = parent_of[node]
    path.reverse()
    return path

Code Snippet — A*

def astar(graph: WeightedGraph, start_node: int, goal_node: int,
          heuristic) -> list[int]:
    """Find cheapest path using cost + heuristic estimate."""
    num_nodes = graph.num_nodes
    cost_to_reach = [float('inf')] * num_nodes
    parent_of = [-1] * num_nodes
    visited = [False] * num_nodes

    cost_to_reach[start_node] = 0
    estimated_total = heuristic(start_node, goal_node)

    # Priority queue: (f_score, node)
    frontier = [(estimated_total, start_node)]

    while frontier:
        frontier.sort()
        current_f_score, current_node = frontier.pop(0)

        if visited[current_node]:
            continue
        visited[current_node] = True

        if current_node == goal_node:
            break

        for neighbor, edge_weight in graph.get_neighbors(current_node):
            if visited[neighbor]:
                continue
            new_cost = cost_to_reach[current_node] + edge_weight
            if new_cost < cost_to_reach[neighbor]:
                cost_to_reach[neighbor] = new_cost
                parent_of[neighbor] = current_node
                f_score = new_cost + heuristic(neighbor, goal_node)
                frontier.append((f_score, neighbor))

    # Reconstruct path
    path = []
    node = goal_node
    while node != -1:
        path.append(node)
        node = parent_of[node]
    path.reverse()
    return path


def manhattan_distance(node_a: int, node_b: int, grid_cols: int) -> int:
    """Admissible heuristic for grid-based pathfinding."""
    row_a, col_a = node_a // grid_cols, node_a % grid_cols
    row_b, col_b = node_b // grid_cols, node_b % grid_cols
    return abs(row_a - row_b) + abs(col_a - col_b)

When to Use Which

ScenarioAlgorithmWhy
Unweighted graphBFSSimpler, same result as Dijkstra with weight=1
Weighted graph, no goal infoDijkstraExplores uniformly by cost
Weighted graph, known goal positionA*Fewer nodes explored with good heuristic
Negative edge weightsNeitherUse Bellman-Ford instead

The Visual Difference

On a weighted maze, Dijkstra explores in expanding cost-circles (avoiding expensive edges), while A* focuses exploration toward the exit. Both find the same cheapest path, but A* gets there by exploring fewer cells.