Note: this question is not a duplicate of the following questions: How to remove vertices from a graph that are not coverable by cliques? How to remove vertices from a graph while preserving clique coverage of specific vertices? This question is with respect to removing vertices that are not reachable from a set of vertices, regardless of clique membership.
How can I remove vertices from a graph that are not reachable from a given set of vertices?
Here is a toy example and solution:
In the graph below, I want to remove the vertices that are not reachable from any vertex with an "x". The orange vertices are the vertices to be removed.
The current approach is doing depth-first search from each of the vertices marked with an "x", and keeping track of which vertices are visited. All vertices from the graph that are not in that set of visited vertices are removed from the graph. However, this could take a while if the graph is large, so I was wondering if there is a faster way of doing this.