Graph Theory37 sections · 1633 units
Open in Course

The Data Structure

Stack vs Queue

DFS uses a stack (Last-In-First-Out). The most recent node gets processed first, pushing you deeper into the graph. BFS uses a queue (First-In-First-Out). The oldest unprocessed node gets handled first, keeping you at the same depth level. When you visit a node's neighbors in BFS, you add them to the back of the queue.

By the time you process them, you have finished all nodes at the current level. This queue discipline creates the level-by-level exploration pattern that makes BFS find shortest paths.