• 图的遍历, 美团笔试题


    import java.util.*;
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n =sc.nextInt();
            List<Integer>[] g = new ArrayList[n+1];
            for(int i=1; i <= n; i++) {
                g[i] = new ArrayList<Integer>();
            }
            for(int i=1; i < n; i++) {
                int a = sc.nextInt(), b = sc.nextInt();
                g[a].add(b); g[b].add(a);
            }
            int pathLen = 0;
            boolean[] used = new boolean[n+1];
            Queue<Integer> q = new LinkedList<>();
            q.offer(1); used[1] = true;
            while(!q.isEmpty()) {
                int size = q.size();
                pathLen ++;
                for(int i=0; i < size; i++) {
                    int cur = q.poll();
                    for(int j=0; j < g[cur].size(); j++) {
                        int x = g[cur].get(j);
                        if(used[x] == false) {
                            used[x] = true;
                            q.offer(x);
                        }
                    }
                }
            } 
            System.out.println(2*(n-1)-(pathLen-1));
        }
    }
    
    
    
  • 相关阅读:
    LeetCode 21. 合并两个有序链表
    LeetCode 20. 有效的括号
    LeetCode 19. 删除链表的倒数第N个节点
    AI
    http
    IP地址
    wiodows /linux CMD
    git
    AI
    JS常用的获取值和设值的方法
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13187245.html
Copyright © 2020-2023  润新知