This repository acts as a personal archive for my solutions to EdX course *Data Structures and Software Design* from PennX.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
849 B

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. /*
  4. * SD2x Homework #6
  5. * This is an implementation of Depth First Search (DFS) on a graph.
  6. * You may modify and submit this code if you'd like.
  7. */
  8. public class DepthFirstSearch {
  9. protected Set<Node> marked;
  10. protected Graph graph;
  11. public DepthFirstSearch(Graph graphToSearch) {
  12. marked = new HashSet<Node>();
  13. graph = graphToSearch;
  14. }
  15. public boolean dfs(Node start, String elementToFind) {
  16. if (!graph.containsNode(start)) {
  17. return false;
  18. }
  19. if (start.getElement().equals(elementToFind)) {
  20. return true;
  21. } else {
  22. marked.add(start);
  23. for (Node neighbor : graph.getNodeNeighbors(start)) {
  24. if (!marked.contains(neighbor) &&
  25. dfs(neighbor, elementToFind))
  26. return true;
  27. }
  28. return false;
  29. }
  30. }
  31. }