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.

52 lines
1.2 KiB

  1. import java.util.HashSet;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. import java.util.Set;
  5. /*
  6. * SD2x Homework #6
  7. * This is an implementation of Breadth First Search (BFS) on a graph.
  8. * You may modify and submit this code if you'd like.
  9. */
  10. public class BreadthFirstSearch {
  11. protected Set<Node> marked;
  12. protected Graph graph;
  13. public BreadthFirstSearch(Graph graphToSearch) {
  14. marked = new HashSet<Node>();
  15. graph = graphToSearch;
  16. }
  17. /**
  18. * This method was discussed in the lesson
  19. */
  20. public boolean bfs(Node start, String elementToFind) {
  21. if (!graph.containsNode(start)) {
  22. return false;
  23. }
  24. if (start.getElement().equals(elementToFind)) {
  25. return true;
  26. }
  27. Queue<Node> toExplore = new LinkedList<Node>();
  28. marked.add(start);
  29. toExplore.add(start);
  30. while (!toExplore.isEmpty()) {
  31. Node current = toExplore.remove();
  32. for (Node neighbor : graph.getNodeNeighbors(current)) {
  33. if (!marked.contains(neighbor)) {
  34. if (neighbor.getElement().equals(elementToFind)) {
  35. return true;
  36. }
  37. marked.add(neighbor);
  38. toExplore.add(neighbor);
  39. }
  40. }
  41. }
  42. return false;
  43. }
  44. }