Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. public static boolean test(HashMap<Integer, List<Integer>> graph, int start, int finish) {
  2. HashSet<Integer> points = graph.values().stream().flatMap(List::stream).collect(Collectors.toCollection(HashSet::new));
  3. points.addAll(graph.keySet());
  4. LinkedList<Integer> queue = new LinkedList<>();
  5. HashMap<Integer, Boolean> visited = new HashMap<>();
  6.  
  7. for (int i = 1; i <= points.size(); i++) {
  8. visited.put(i, false);
  9. }
  10. visited.put(start, true);
  11. queue.push(start);
  12.  
  13.  
  14. while (!queue.isEmpty()) {
  15. int current = queue.pop();
  16. System.out.print(current + " ");
  17. List<Integer> neighbours = graph.get(current);
  18. System.out.println(visited);
  19. if (neighbours == null) {
  20. continue;
  21. }
  22. for (Integer neighbor : neighbours) {
  23. if (!visited.get(neighbor)) {
  24. queue.add(neighbor);
  25. visited.put(neighbor, true);
  26. }
  27. }
  28. }
  29. return false;
  30. }
  31.  
  32. public static void main(String[] args) {
  33. HashMap<Integer, List<Integer>> graph = new HashMap<Integer, List<Integer>>();
  34. graph.put(1, List.of(2, 3, 4));
  35. graph.put(2, List.of(3, 4, 5));
  36. graph.put(3, List.of(6));
  37. test(graph, 2, 1);
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement