Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class HW1 {
- public static void main(String[] args){
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- ArrayList<Node> nodes = new ArrayList<>();
- for(int i = 0; i<n; i++){
- nodes.add(new Node());
- }
- for(int i = 0; i<n-1; i++){
- int a = sc.nextInt()-1;
- int b = sc.nextInt()-1;
- nodes.get(a).arc.add(nodes.get(b));
- nodes.get(b).arc.add(nodes.get(a));
- }
- DFS(nodes.get(0));
- for(Node node: nodes){
- System.out.print(node.dis + " ");
- }
- }
- public static void DFS(Node cur){
- cur.visited = true;
- for(Node next: cur.arc){
- if(!next.visited){
- DFS(next);
- if(cur.dis<next.dis+1){
- cur.dis = next.dis+1;
- }
- }
- }
- }
- }
- class Node{
- boolean visited;
- ArrayList<Node> arc;
- int dis;
- Node(){
- visited = false;
- arc = new ArrayList<>();
- dis = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement