AlgoFrames

Spot the bug: when to mark seen

Standard · Find the bug · about 8 min

This bfsOrder should list each reachable node once, in BFS order. On graphs with a cycle it lists some nodes twice.

Click the faulty line, then fix the code.

Example 1

Input:

[{"n":3,"edges":[[0,1],[0,2],[1,2]],"directed":false},0]

Output:

[0,1,2]

The buggy code returns [0, 1, 2, 2].

Constraints

  • 1 ≤ n ≤ 200 nodes, numbered 0 to n - 1
  • 0 ≤ source < n
  • At most 3n edges; repeated edges and self-loops may appear

Learn the idea first: Breadth-first search, a visual lesson.

More Breadth-first search problems