logologo

图的广度优先遍历(BFS)

Oct 13, 2023

public static void bfs(Node start) {
  if (start == null)
    return;
  Queue<Node> queue = new LinkedList<>();
  HashSet<Node> set = new HashSet<>();
  queue.add(start);
  set.add(start);

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

C++Java
浙ICP备2021022773号    2022-PRESENT © ZhengKe