To guarantee the shortest path, A* assigns a "cost" to every generated node on the grid. It always explores the node with the lowest total cost F:
// The Core Equation:
F = G + H
// G is distance from start node
G(n) = distance(start, n)
// H is estimated distance to end
H(n) = heuristic(n, end)
By combining G(how far we've traveled) with H (our best guess of how far we have left), A* acts like a guided laser, zooming directly towards the target rather than radially expanding in all directions like a flood-fill.