Learn how algorithms explore networks, solve mazes, and find reachable places.
Graphs model networks of connected points. Search algorithms visit those points systematically. Breadth-first search explores nearby points first, while depth-first search follows one path as far as it can.
Start at A and visit its immediate neighbours, B and C. Then visit the unvisited neighbours of B and C. The search expands outward in layers, like ripples spreading across a pond.
Breadth-first search uses a first-in, first-out queue. Add a node when you discover it, then remove the oldest queued node to explore its neighbours. Marking nodes when discovered prevents duplicate visits.
Depth-first search starts at A, chooses one unvisited neighbour, and keeps going. It can visit A, B, D, then backtrack to E, before returning to explore C and F. A stack, or recursion, remembers where to return.
A depth-first implementation uses last-in, first-out behaviour. The newest discovered node is explored first. Recursion provides this stack automatically, while an explicit stack gives you direct control over the same process.
Both traversals visit every reachable vertex and edge once with an adjacency list. BFS finds shortest paths by number of edges in an unweighted graph. DFS is useful for backtracking, components, and cycle analysis, but it does not guarantee a shortest path.
Do not confuse the shortest route with the first route DFS happens to find. In a maze, BFS can guarantee the fewest steps when every move costs the same. If moves have different costs, use a weighted shortest-path algorithm instead.