有苦有乐的算法 --- 图的宽度优先遍历

该代码展示了如何使用队列对图进行宽度优先遍历(BFS)。首先检查起点是否为空,然后利用LinkedList创建队列并初始化HashSet用于记录已访问节点。接着,将起点入队,并在循环中不断弹出队首节点打印其值,同时遍历其邻居节点,若未被访问则加入队列和已访问集合。整个过程确保了图的BFS遍历正确进行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

给定一个图,使用队列对其进行宽度优先遍历

代码

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);
			}
		}
	}
}
public 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<>();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值