Guest User

Untitled

a guest
Jun 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. //package whatever; // don't place package name!
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. class TopologicalSort {
  7.  
  8. static class GraphNode {
  9. int value;
  10.  
  11. List<GraphNode> neighbors;
  12.  
  13. public GraphNode(int x) {
  14. this.value = x;
  15. this.neighbors = new ArrayList<>();
  16. }
  17. }
  18.  
  19. static void topologicalSort(GraphNode node) {
  20.  
  21. Deque<GraphNode> stack = new ArrayDeque<>();
  22. Set<Integer> visitedNodes = new HashSet<>();
  23. topologicalSort(node, stack, visitedNodes);
  24. while (!stack.isEmpty()) {
  25. System.out.println(stack.pop().value);
  26. }
  27.  
  28. }
  29.  
  30. // 0 : 1, 3
  31. // 3 : 4
  32. // 4
  33. // stack : 2, 1, 4, 3, 0
  34. static void topologicalSort(GraphNode node, Deque<GraphNode> stack, Set<Integer> visitedNodes) {
  35. // first mark it as visited
  36. if (visitedNodes.contains(node.value)) {
  37. return;
  38. }
  39.  
  40. visitedNodes.add(node.value);
  41. for (GraphNode neighbor : node.neighbors) {
  42. topologicalSort(neighbor, stack, visitedNodes);
  43. }
  44. stack.offerFirst(node);
  45. }
  46.  
  47. public static void main(String[] args) {
  48. System.out.println("Hello Java");
  49.  
  50. GraphNode zero = new GraphNode(0);
  51. GraphNode one = new GraphNode(1);
  52. GraphNode two = new GraphNode(2);
  53. GraphNode three = new GraphNode(3);
  54. GraphNode four = new GraphNode(4);
  55.  
  56. zero.neighbors.add(three);
  57. zero.neighbors.add(one);
  58. one.neighbors.add(two);
  59. three.neighbors.add(four);
  60. four.neighbors.add(two);
  61. topologicalSort(zero);
  62. }
  63. }
Add Comment
Please, Sign In to add comment