图的遍历(广度优先遍历、深度优先遍历)

小灰灰 2022-02-05 08:45 601阅读 0赞

图的数据结构

https://blog.csdn.net/weixin_43093501/article/details/89840219

广度优先遍历

思路

准备:队列、set:查重
1.将图的起始节点添加到队列中,同时加到set中
2.只要队列中有元素,就执行代码
3.弹出队列中的元素,并打印,
4.将该元素的邻居节点集合全部加入到队列中(重复的不加)
在这里插入图片描述

代码

  1. public static void bfs(Node node) {
  2. if (node == null) {
  3. return;
  4. }
  5. Queue<Node> queue = new LinkedList<>();
  6. HashSet<Node> map = new HashSet<>();
  7. queue.add(node);
  8. map.add(node);
  9. while (!queue.isEmpty()) {
  10. Node cur = queue.poll();
  11. System.out.println(cur.value);
  12. for (Node next : cur.nexts) {
  13. if (!map.contains(next)) {
  14. map.add(next);
  15. queue.add(next);
  16. }
  17. }
  18. }
  19. }

深度优先遍历

思路

准备:栈,set(查重)
1.将图的起始节点添加到栈中,同时加到set中
2.只要队列中有元素,就执行代码
3.弹出栈顶元素
4.遍历元素的邻居集合
5.如果邻居节点不重复(不在set中),则:

  • 将刚弹出的栈顶元素加入栈中,
  • 邻居节点加入栈中,
  • 邻居节点加入set中,
  • 打印邻居节点。
    在这里插入图片描述

代码

  1. public static void dfs(Node node) {
  2. if (node == null) {
  3. return;
  4. }
  5. Stack<Node> stack = new Stack<>();
  6. HashSet<Node> set = new HashSet<>();
  7. stack.add(node);
  8. set.add(node);
  9. System.out.println(node.value);
  10. while (!stack.isEmpty()) {
  11. Node cur = stack.pop();
  12. for (Node next : cur.nexts) {
  13. if (!set.contains(next)) {
  14. stack.push(cur);
  15. stack.push(next);
  16. set.add(next);
  17. System.out.println(next.value);
  18. break;
  19. }
  20. }
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,601人围观)

还没有评论,来说两句吧...

相关阅读