Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1.     /**
  2.      * An interface representing what should happen during a search.
  3.      *
  4.      * @param <T>
  5.      */
  6.     public static interface SearchConsumer<T> {
  7.         void consume(T t);
  8.         void circleFound();
  9.         boolean ready();
  10.     }
  11.    
  12.     /**
  13.      * Performs Depth First Search on the graph. Uses a consumer to determine when
  14.      * the search is over and which actions to perform.
  15.      *
  16.      * @param startNode
  17.      */
  18.     public void depthFirstSearch(T startNode, SearchConsumer<T> consumer) {
  19.         Stack<T> dfsStack = new Stack<>();
  20.         HashMap<T, Boolean> visited = new HashMap<>();
  21.         nodes.forEach(t -> visited.put(t, Boolean.FALSE));
  22.         dfsStack.push(startNode);
  23.         visited.put(startNode, Boolean.TRUE);
  24.         consumer.consume(startNode);
  25.         do {
  26.             T current = dfsStack.pop();
  27.             Set<T> neighbours = neighbourMap.get(current);
  28.             Set<T> neighboursToConsider = getSearchNodesToConsider(current, neighbours);
  29.             for(T t : neighboursToConsider) {
  30.                 if(!visited.get(t)) {
  31.                     dfsStack.push(t);
  32.                     consumer.consume(t);
  33.                     visited.put(t, Boolean.TRUE);
  34.                 } else {
  35.                     consumer.circleFound();
  36.                 }
  37.             }
  38.         } while(!consumer.ready() && !dfsStack.isEmpty());
  39.     }
  40.    
  41.     /**
  42.      * When performing D/B- FS (or any other search) this method is used to determine the set of neighbours
  43.      * that have to be considered from a certain node. For general graphs this is the whole set of neighbours of a node.
  44.      *
  45.      * @param current
  46.      * @param neighbours
  47.      * @return
  48.      */
  49.     protected Set<T> getSearchNodesToConsider(T current, Set<T> neighbours){
  50.         return neighbours;
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement