156 return edges;
157 }
158
159 public Set<T> adjacentNodes(T u) {
160 return edges.get(u);
161 }
162
163 public boolean contains(T u) {
164 return nodes.contains(u);
165 }
166
167 /**
168 * Returns nodes sorted in topological order.
169 */
170 public Stream<T> orderedNodes() {
171 TopoSorter<T> sorter = new TopoSorter<>(this);
172 return sorter.result.stream();
173 }
174
175 /**
176 * Traverse this graph and performs the given action in topological order
177 */
178 public void ordered(Consumer<T> action) {
179 TopoSorter<T> sorter = new TopoSorter<>(this);
180 sorter.ordered(action);
181 }
182
183 /**
184 * Traverses this graph and performs the given action in reverse topological order
185 */
186 public void reverse(Consumer<T> action) {
187 TopoSorter<T> sorter = new TopoSorter<>(this);
188 sorter.reverse(action);
189 }
190
191 /**
192 * Returns a transposed graph from this graph
193 */
194 public Graph<T> transpose() {
195 Builder<T> builder = new Builder<>();
196 nodes.stream().forEach(builder::addNode);
197 // reverse edges
198 edges.keySet().forEach(u -> {
199 edges.get(u).stream()
200 .forEach(v -> builder.addEdge(v, u));
201 });
202 return builder.build();
203 }
204
205 /**
206 * Returns all nodes reachable from the given root.
207 */
208 public Set<T> dfs(T root) {
209 return dfs(Set.of(root));
210 }
211
212 /**
|
156 return edges;
157 }
158
159 public Set<T> adjacentNodes(T u) {
160 return edges.get(u);
161 }
162
163 public boolean contains(T u) {
164 return nodes.contains(u);
165 }
166
167 /**
168 * Returns nodes sorted in topological order.
169 */
170 public Stream<T> orderedNodes() {
171 TopoSorter<T> sorter = new TopoSorter<>(this);
172 return sorter.result.stream();
173 }
174
175 /**
176 * Traverses this graph and performs the given action in topological order.
177 */
178 public void ordered(Consumer<T> action) {
179 TopoSorter<T> sorter = new TopoSorter<>(this);
180 sorter.ordered(action);
181 }
182
183 /**
184 * Traverses this graph and performs the given action in reverse topological order.
185 */
186 public void reverse(Consumer<T> action) {
187 TopoSorter<T> sorter = new TopoSorter<>(this);
188 sorter.reverse(action);
189 }
190
191 /**
192 * Returns a transposed graph from this graph.
193 */
194 public Graph<T> transpose() {
195 Builder<T> builder = new Builder<>();
196 nodes.stream().forEach(builder::addNode);
197 // reverse edges
198 edges.keySet().forEach(u -> {
199 edges.get(u).stream()
200 .forEach(v -> builder.addEdge(v, u));
201 });
202 return builder.build();
203 }
204
205 /**
206 * Returns all nodes reachable from the given root.
207 */
208 public Set<T> dfs(T root) {
209 return dfs(Set.of(root));
210 }
211
212 /**
|