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) Remembersrcitself counts as 1.
Input
- Line 1:
V E(vertices, edges). - Next
Elines:u v, a directed edgeu → 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).