BFS代码核心框架

一、BFS:使用队列保存未被检测的点,结点按照宽度优先的次序被访问和进出队列。
下面用树来讲述BFS。
请添加图片描述

例题 牛客网NC15

请添加图片描述
请添加图片描述

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null) return res;
        queue.offer(root);
        while(!queue.isEmpty()){
            ArrayList<Integer> path = new ArrayList<>();
            int size = queue.size();
            while(size-->0){
                TreeNode node = queue.poll();
                path.add(node.val);
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
            res.add(path);
        }
        return res;
    }
}

框架

public static int BFS(node root){
	Deque<node> queue = new ArrayDeque<>();//BFS队列
	Set<node> visited = new HashSet<>();//访问标记
	
	q.addLast(root);//将首个节点入队
	visited.add(root);
	
	while(!queue.isEmpty()){
		int sz = queue.size();
		for(int i=0; i<sz; i++){
			node cur = queue.removeFirst();
			将这层的值cur放到指定层数组;
			(或)如果出现目标态,则做相关处理;
			for(Node x : cur的相邻元素){//把相邻的节点入队,作为下一层
				q.addLast(x);
				visited.add(x);//防止走回头路
			}
		}
	}
	return 0;
}

二、BFS的其他用法及框架

1.计算从start到target的距离

public static int BFS(node star, node target){
	Deque<node> queue = new ArrayDeque<>();
	Set<node> visited = new HashSet<>();
	
	q.addLast(start);
	visited.add(start);
	int res = 0;
	
	while(!queue.isEmpty()){
		int sz = queue.size();
		for(int i=0; i<sz; i++){
			node cur = queue.removeFirst();
			if(cur等于target)
				return res;
			for(Node x : cur的相邻元素){
				if(!visited.contains(x)){//x没有被访问过
					q.addLast(x);
					visited.add(x);//防止走回头路
				}
			}
		}
		res++;
	}
	return 0;
}

例题可参考:https://blog.csdn.net/weixin_47525457/article/details/119975041

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值