Some insights on breadth-first search

It ’s not a comprehension, it ’s just some thoughts. The BFS of the tree is very simple, and it should be familiar with the road, that is, put the node in the queue, and put his child nodes into it every time, without brain traversal, because the tree is equivalent to Directed graph, so there is no need to mark whether each point has been traversed, because each point must be traversed only once, but today I encountered the BFS of the graph. To be honest, the graph has not been reviewed, so for this kind of problem, the idea Still not so clear, this question is listed below:

We first look at the application of trees, but slowly we will find that we are looking for one layer at a time. Put as many points as possible on the first layer. The last layer must meet the requirements, so we simulate The adjacency list and out-degree and in-degree (this question is undirected, there is a display in the question, it becomes degree), every time the degree 1 is added to the queue, BFS is enough, the last layer is left, using a linked list To undertake, by the way, jdk1.8Hashmap is an array, linked list, red-black tree, if the length of the linked list is greater than 8, then it becomes a red-black tree, and if the number of red-black trees is less than 6, then it becomes a linked list, and the load factor is 0.75. Ok, after reviewing, list the code:

public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> ans = new ArrayList<>();
        if (n == 1) {
            ans.add(0);
            return ans;
        }
        int[] degree = new int[n];
        List<List<Integer>> map = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            map.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            degree[edge[0]]++;
            degree[edge[1]]++;
            map.get(edge[0]).add(edge[1]);
            map.get(edge[1]).add(edge[0]);
        }
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if (degree[i] == 1) {
                queue.offer(i);
            }
        }
        while (!queue.isEmpty()) {
            ans = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int cur = queue.poll();
                ans.add(cur);
                List<Integer> nexts = map.get(cur);
                for (Integer next : nexts) {
                    degree[next]--;
                    if (degree[next] == 1) {
                        queue.offer(next);
                    }
                }
            }
        }
        return ans;
    }

go to bed now ~

Published 17 original articles · Likes0 · Visits 148

Guess you like

Origin blog.csdn.net/qq_33286699/article/details/105189580