BeginnerTopic 26 of 104Software & Computing

BFS and DFS

Breadth-first and depth-first traversals explore graphs.

In depth

BFS explores neighbours level by level using a queue and finds shortest paths in unweighted graphs; DFS dives deep using a stack or recursion and supports topological sort, cycle detection and connected components. Both run in O(V+E).

Key points

  • Visited set avoids loops
  • Level order
  • Backtracking relation
Example

A maze solver uses BFS to find the shortest path.

Why it matters

Breadth-first and depth-first searches explore graphs systematically, and they are the basis of many graph algorithms.

Where this is used

  • Finding the fewest hops between two users in a social network with BFS.
  • Checking whether a dependency graph contains a cycle with DFS.
  • Testing whether a maze has a path from start to exit.

Frequently asked questions

What is BFS and DFS?

Breadth-first and depth-first traversals explore graphs.

Why is it important to understand BFS and DFS?

Breadth-first and depth-first searches explore graphs systematically, and they are the basis of many graph algorithms.

When should I use BFS rather than DFS?

Use BFS to find shortest paths measured in hops, and DFS for tasks such as topological ordering or exploring all paths.

Why does BFS use a queue?

The queue keeps nodes in order of distance from the start, so each level is explored before the next.

How is BFS and DFS used in practice?

Typical applications include finding the fewest hops between two users in a social network with BFS, checking whether a dependency graph contains a cycle with DFS and testing whether a maze has a path from start to exit.

What should I learn before BFS and DFS?

Study "Graphs" first (topic 25 of 104 in Software & Computing). It covers the groundwork this topic builds on.

What are the key points of BFS and DFS?

Visited set avoids loops. Level order. Backtracking relation.

Can you give an example of BFS and DFS?

A maze solver uses BFS to find the shortest path.

What comes after BFS and DFS?

The next topic is "Shortest path algorithms", which builds directly on this one.

How difficult is BFS and DFS?

It is classed as Beginner in Software & Computing (topic 26 of 104). It is an entry-level topic. It relies only on basic school mathematics and the ideas introduced earlier in this discipline.

Learning path

Want to practise? Open the interactive course for quick checks, quizzes, simulations and progress tracking.