logologo

图的深度优先遍历(DFS)

Oct 13, 2023

public static void dfs(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.empty()) {
    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;
      }
    }
  }
}


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