算法-图-深度优先遍历

2022-4-14 diaba 数据结构

package com.jiucaiyuan.net.algrithm.graph;

import java.util.HashSet;
import java.util.Stack;

/**
 * 图的深度优先遍历
 *
 * @Author jiucaiyuan  2022/4/14 18:10
 * @mail services@jiucaiyuan.net
 */

public class GraphMaxDepthAccess {
    /**
     * 深度优先遍历
     *
     * @param node 从node开始遍历
     */
    public static void bfs(Node node) {
        if (node == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        //标记已入栈
        HashSet<Node> set = new HashSet<>();
        stack.push(node);
        set.add(node);
        System.out.println(node.value);
        while (!stack.isEmpty()) {
            Node curr = stack.pop();
            for (Node next : curr.nexts) {
                if (!set.contains(next)) {
                    //当前节点重新入栈
                    stack.push(curr);
                    //当前节点的下一个节点入栈
                    stack.push(next);
                    set.add(next);
                    //访问当前节点的下一个节点
                    System.out.println(next.value);
                    //退出循环,会接着处理栈,出栈的是next
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
    }
}

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022