I have a directed acyclic graph and an origin vertex v
in that graph.
How can I visit all the vertices that are reachable from v
, in such a way that if I visit v1
I already visited all the vertices that have and edge to v1
?
Example:
/-----V
A->B->C
Starting from A
, C
must be visited after B
.
I tried just doing a BFS and checking the parents of each vertex and if they are not visited re-add it for later, but that proved too slow, and I believe can be O(v^2)
.
It might help to know that the graph is somewhat binary, each vertex will be pointed to by at most two vertices. In the other direction, each vertex points to a lot of vertices.