Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1.  
  2.  
  3. import java.util.*;
  4.  
  5. /**
  6. *
  7. * @author Colin Lee
  8. */
  9. public class Trees {
  10.  
  11. /**
  12. * @param args the command line arguments
  13. */
  14. public static void main(String[] args) {
  15. HashMap graph = new HashMap();
  16.  
  17. ArrayList v0 = new ArrayList();
  18.  
  19. ArrayList v1 = new ArrayList();
  20. ArrayList v2 = new ArrayList();
  21. ArrayList v3 = new ArrayList();
  22. ArrayList v4 = new ArrayList();
  23. v0.add(1);
  24. v0.add(3);
  25. v1.add(0);
  26. v1.add(4);
  27. v1.add(2);
  28. v2.add(1);
  29. v4.add(1);
  30. v3.add(0);
  31. graph.put(0,v0);
  32. graph.put(1,v1);
  33. graph.put(2,v2);
  34. graph.put(3,v3);
  35. graph.put(4,v4);
  36. HashMap visited = new HashMap();
  37. Stack T = new Stack();
  38. int count;
  39.  
  40. T.push(graph.get(0)); //l(v) = 0 for all v
  41. count = 1; //count = 1
  42. for(int i = 0; i < graph.size(); i++) //(Lv0) = count
  43. visited.put(i, 0);
  44. visited.put(0, count);
  45. while(!T.empty()) { //while T =/= null
  46. ArrayList v = new ArrayList();
  47. v = (ArrayList) T.peek(); //v as top of stack
  48. boolean adjacent = false;
  49. for(int j = 0; j<graph.size(); j++)
  50. if(v.contains(j)&&visited.get(j)==0){
  51. count++; //count = count +1
  52. visited.put(j, count); //l(w) = count
  53. T.push(graph.get(j)); //put w into the stack
  54. adjacent=true;
  55. break;
  56. }
  57. if (!adjacent)
  58. T.pop();
  59.  
  60.  
  61. }
  62. for(int i = 0; i < visited.size(); i++)
  63. System.out.println(i + " " + visited.get(i));
  64.  
  65.  
  66.  
  67.  
  68. // TODO code application logic here
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement