public Set < T > dfs ( Set < T > roots ) { Deque < T > deque = new LinkedList <> ( roots ) ; Set < T > visited = new HashSet <> ( ) ; while ( ! deque . isEmpty ( ) ) { T u = deque . pop ( ) ; if ( ! visited . contains ( u ) ) { visited . add ( u ) ; if ( contains ( u ) ) { adjacentNodes ( u ) . stream ( ) . filter ( v -> ! visited . contains ( v ) ) . forEach ( deque :: push ) ; } } } return visited ; }
Returns all nodes reachable from the given set of roots .