Advertisement
Guest User

Problemset 4 - HW1 (DFS)

a guest
Jun 19th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3.  
  4. public class HW1 {
  5. public static void main(String[] args){
  6. Scanner sc = new Scanner(System.in);
  7. int n = sc.nextInt();
  8. ArrayList<Node> nodes = new ArrayList<>();
  9. for(int i = 0; i<n; i++){
  10. nodes.add(new Node());
  11. }
  12. for(int i = 0; i<n-1; i++){
  13. int a = sc.nextInt()-1;
  14. int b = sc.nextInt()-1;
  15. nodes.get(a).arc.add(nodes.get(b));
  16. nodes.get(b).arc.add(nodes.get(a));
  17. }
  18. DFS(nodes.get(0));
  19. for(Node node: nodes){
  20. System.out.print(node.dis + " ");
  21. }
  22. }
  23. public static void DFS(Node cur){
  24. cur.visited = true;
  25. for(Node next: cur.arc){
  26. if(!next.visited){
  27. DFS(next);
  28. if(cur.dis<next.dis+1){
  29. cur.dis = next.dis+1;
  30. }
  31. }
  32. }
  33. }
  34. }
  35. class Node{
  36. boolean visited;
  37. ArrayList<Node> arc;
  38. int dis;
  39. Node(){
  40. visited = false;
  41. arc = new ArrayList<>();
  42. dis = 0;
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement