图的遍历算法

/**
     * 从某个节点开始宽度优先遍历,也叫广度优先遍历
     *
     * @param node
     */
    public static void bfs(Node node) {
        if (node == null) {
            return;
        }
        Deque queue = new LinkedList<>();
        Set set = new HashSet<>();
        queue.add(node);
        set.add(node);
        while (!queue.isEmpty()) {
            Node poll = queue.poll();
            System.out.println(poll.value);
            for (Node next : poll.nexts) {
                if (!set.contains(next)) {
                    queue.add(next);
                    set.add(next);
                }
            }
        }
    }

    /**
     * 深度优先遍历,
     *
     * @param node
     */
    public static void dfs(Node node) {
        if (node == null) {
            return;
        }
        Deque stack = new LinkedList<>();
        Set set = new HashSet<>();
        stack.add(node);
        set.add(node);
        System.out.println(node.value);
        while (!stack.isEmpty()) {
            Node pop = stack.pop();
            for (Node next : pop.nexts) {
                if (!set.contains(next)) {
                    stack.push(pop);
                    stack.push(next);
                    set.add(next);
                    System.out.println(next.value);
                    break;
                }
            }
        }
    }

 

你可能感兴趣的:(leetcode题解)