Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * An interface representing what should happen during a search.
- *
- * @param <T>
- */
- public static interface SearchConsumer<T> {
- void consume(T t);
- void circleFound();
- boolean ready();
- }
- /**
- * Performs Depth First Search on the graph. Uses a consumer to determine when
- * the search is over and which actions to perform.
- *
- * @param startNode
- */
- public void depthFirstSearch(T startNode, SearchConsumer<T> consumer) {
- Stack<T> dfsStack = new Stack<>();
- HashMap<T, Boolean> visited = new HashMap<>();
- nodes.forEach(t -> visited.put(t, Boolean.FALSE));
- dfsStack.push(startNode);
- visited.put(startNode, Boolean.TRUE);
- consumer.consume(startNode);
- do {
- T current = dfsStack.pop();
- Set<T> neighbours = neighbourMap.get(current);
- Set<T> neighboursToConsider = getSearchNodesToConsider(current, neighbours);
- for(T t : neighboursToConsider) {
- if(!visited.get(t)) {
- dfsStack.push(t);
- consumer.consume(t);
- visited.put(t, Boolean.TRUE);
- } else {
- consumer.circleFound();
- }
- }
- } while(!consumer.ready() && !dfsStack.isEmpty());
- }
- /**
- * When performing D/B- FS (or any other search) this method is used to determine the set of neighbours
- * that have to be considered from a certain node. For general graphs this is the whole set of neighbours of a node.
- *
- * @param current
- * @param neighbours
- * @return
- */
- protected Set<T> getSearchNodesToConsider(T current, Set<T> neighbours){
- return neighbours;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement