图的宽度优先遍历和深度优先遍历

宽度优先遍历
1.利用队列实现
2.从原节点开始依次按照宽度进队列,然后弹出
3.每弹出一个节点,把该节点所以没有进过队列的邻节点放入队列
4.直到队列变为空

广度优先遍历
1.利用栈实现
2.从原节点开始把节点按照深度放入栈,然后弹出
3.每弹出一个节点,把该节点所有没有进过栈的节点放入栈中
4.直到栈变为空

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


public class GraphBFS{

    public static 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;
			in = 0;
			out = 0;
			nexts = new ArrayList<>();
			edges = new ArrayList<>();
		}
	}

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

	
	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);//加入队列和set,set起注册作用
		while(!queue.isEmpty()){
			Node cur = queue.poll();
			System.out.println(cur.value);//该步为处理,具体看题目情况
			for(Node next : cur.nexts){//遍历该点的邻居点
				if(!set.contains(next)){//如果没有在set中出现过,那么就加到set和队列中
					set.add(next);
					queue.add(next);
				}
			}
		}
	}

	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.isEmpty()){
			Node cur = stack.pop();
			for(Node next : cur.nexts){//遍历该点的邻居
				if(!set.contains(next)){
					stack.push(cur);//如果该点的邻居没有在set中,把他重新入栈
					stack.push(next);
					set.add(cur);
					System.out.println(next.value);
					break;//处理完他的一个邻居节点后直接break就行,其余邻居节点不用处理
				}
			}
		}
	}
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值