CleverSphere

Breadth-first and depth-first search

Both methods visit every reachable vertex, but in a different order.

Rules

  • BFS: queue, level by level
  • DFS: stack or recursion, depth first
  • Mark visited vertices

Your turn

Three problems on this topic. Separate lists with commas.

  1. 1 · BFS & DFS
  2. 2
  3. 3

Breadth-first search from A on the undirected graph. Neighbours in alphabetical order. In which order are the vertices visited?

EdgeWeight
A – B6
B – C1
B – D4
B – E2
A – E3
D – E4

Reihenfolge (comma-separated)

Worked example

Depth-first search from A on the undirected graph. Neighbours in alphabetical order. In which order are the vertices visited?

EdgeWeight
A – B7
B – C8
B – D6
C – E3
A – F3
F – G6
D – F5
B – F7

Worked solution

  1. 1A → B → C → E → D → F → G

Typical mistake: Breadth-first uses a queue, depth-first goes as deep as possible first.

Common questions

Which one finds shortest paths?

In unweighted graphs, breadth-first search.

Related

More topics