目 录CONTENT

文章目录

图的深度优先遍历

小磊
2023-04-25 / 0 评论 / 0 点赞 / 672 阅读 / 93 字 / 正在检测是否收录...

图的深度优先遍历

/**
 * 深度优先遍历,使用栈来实现
 */
public class DFS {

    public void bfs(Node node) {
        if (null == node) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        Set<Node> set = new HashSet<>();
        stack.add(node);
        set.add(node);
        System.out.println(node.value);
        while (!stack.isEmpty()){
            Node pop = stack.pop();
            for (Node n: pop.next){
                if(!set.contains(n)){
                    stack.add(pop);
                    stack.add(n);
                    System.out.println(n.value);
                    set.add(n);
                    break;
                }
            }
        }
    }
}
0

评论区