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


    import java.util.*;

    /**
    * 图的广度优先遍历
    */
    public class BreadthFirst {

    public static void bfs(Node node) {
    if (node == null) {
    return;
    }
    Queue<Node> queue = new LinkedList<>();
    HashSet<Node> set = new HashSet<>();
    queue.add(node);
    set.add(node);
    while (!queue.isEmpty()) {
    Node cur = queue.poll();
    System.out.println(cur.value);
    for (Node next : cur.nexts) {
    if (!set.contains(next)) {
    set.add(next);
    queue.add(next);
    }
    }
    }
    }

    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;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    WebBrowser.ExecWB的完整说明
    jQuery选择器的灵活用法
    Nooice, 首次开通博客园
    【HDU】3663 Power Stations
    【HDU】4069 Squiggly Sudoku
    【FOJ】2076 SUDOKU
    【HDU】3529 Bomberman Just Search!
    【HDU】3909 Sudoku
    【HDU】2780 SuSuSudoku
    【HDU】3111 Sudoku
  • 原文地址:https://www.cnblogs.com/laydown/p/13123820.html
Copyright © 2011-2022 走看看