Depth-first search finds a way, not the shortest one. For the shortest you change the order: first all neighbours of the start, then their neighbours. You spread outward like rings from a stone dropped in water; the first time you reach a node you have reached it in the fewest steps. This is breadth-first search (BFS).
from collections import dequequeue = deque([(start, 0)])seen = {start}while queue:node, steps = queue.popleft()if node == goal:return stepsfor nxt in graph[node]:if nxt not in seen:seen.add(nxt)queue.append((nxt, steps + 1))return -1
This holds where every step costs the same (one square on a grid, one move in a maze). With limited energy, or when looking for the nearest target, the distance as the crow flies misleads you: a near target behind a wall can cost more than a far one in the open. Measure the distance with BFS.