← Back to problems
UNSW COMP2521 · medium

BFS: Number of Reachable Vertices

BFS: how many vertices are reachable from the source

Read a directed graph and a source src, and print the total number of vertices reachable from src (including src itself). BFS or DFS both work.

Complete numReachable: traverse from src, mark every vertex you reach, then count the marked ones.

Pitfalls (straight from the bug lab): (1) you must use visited[], or a cyclic graph loops forever. (2) Mark at the moment of enqueue / first visit, not after processing. (3) Remember src itself counts as 1.

Input

  • Line 1: V E (vertices, edges).
  • Next E lines: u v, a directed edge u → v.
  • Last line: the source src.

Output

  • One line: the number of vertices reachable from src (including itself).

Example: input 4 2 / 0 1 / 1 2 / 0 -> 3 (0 reaches 0, 1, 2 but not 3).