zoukankan      html  css  js  c++  java
  • 图的深度优先遍历


    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Stack;

    /**
    * 图的深度优先遍历
    */
    public class DepthFirst {

    public static void df(Node node) {
    if (node == null) {
    return;
    }
    Stack<Node> stack = new Stack<>();
    HashSet<Node> set = new HashSet<>();
    stack.add(node);
    set.add(node);
    System.out.println(node.value);
    while (!stack.isEmpty()) {
    Node cur = stack.pop();
    for (Node next : cur.nexts) {
    if (!set.contains(next)) {
    stack.push(cur);
    stack.push(next);
    set.add(next);
    System.out.println(next.value);
    break;
    }
    }
    }
    }

    class Graph {

    public HashMap<Integer, Node> nodes;

    public HashSet<Edge> edges;

    public Graph() {
    nodes = new HashMap<>();
    edges = new HashSet<>();
    }

    }

    class Node {

    public int value;

    public int in;

    public int out;

    public ArrayList<Node> nexts;

    public ArrayList<Edge> edges;

    public Node(int value) {
    this.value = value;
    nexts = new ArrayList<>();
    edges = new ArrayList<>();
    }

    }

    class Edge {

    // 权重
    public int weight;

    public Node from;

    public Node to;

    public Edge(int weight, Node from, Node to) {
    this.weight = weight;
    this.from = from;
    this.to = to;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    延时提示框(定时器的使用)
    时间对象
    仿站长之家导航(setTimeout的应用)
    倒计时时钟
    简易网页始终
    网页计算器
    两个数字比较大小
    累加按钮,自加1
    用parsetInt解析数字,并求和
    JS布局转换
  • 原文地址:https://www.cnblogs.com/laydown/p/13123818.html
Copyright © 2011-2022 走看看