Data Structures · Computer science

Graph: BFS vs DFS

Graph: BFS vs DFS is an interactive experiment in Data Structures, a free simulation from StudyFi Lab that runs right in your browser.

Breadth-first search (BFS) takes nodes from a queue, so it visits all neighbours of the start first, then their neighbours — layer by layer, which finds the shortest path in number of edges. Depth-first search (DFS) takes nodes from a stack and goes as deep as it can before backing up. Both visit every node and edge once: O(V + E). BFS powers route finding and “friends of friends”, DFS solves mazes and finds cycles.

Try this: Step from node 0 and compare the queue with the stack. Then change the start to node 7 — the visit orders change completely.

Frequently asked questions

What does the “Graph: BFS vs DFS” experiment show?

Breadth-first search (BFS) takes nodes from a queue, so it visits all neighbours of the start first, then their neighbours — layer by layer, which finds the shortest path in number of edges. Depth-first search (DFS) takes nodes from a stack and goes as deep as it can before backing up. Both visit every node and edge once: O(V + E). BFS powers route finding and “friends of friends”, DFS solves mazes and finds cycles.

How do I try “Graph: BFS vs DFS”?

Step from node 0 and compare the queue with the stack. Then change the start to node 7 — the visit orders change completely.

Studying for a test?

Upload your notes and StudyFi turns them into flashcards, tests and podcasts.

Try StudyFi free