BFS(广度搜索)
一般BFS和数据结构中的队列联系比较紧密
1.算法框架
计算的是迷宫,从起点出发,到达终点,走的步数。
// 计算从起点 start 到终点 target 的最近距离
int BFS(Node start, Node target) {
Queue<Node> q; // 核心数据结构
Set<Node> visited; // 避免走回头路
q.offer(start); // 将起点加入队列
visited.add(start);
int step = 0; // 记录扩散的步数
while (q not empty) {
int sz = q.size();
/* 将当前队列中的所有节点向四周扩散 */
for (int i = 0; i < sz; i++) {
Node cur = q.poll();
/* 划重点:这里判断是否到达终点 */
if (cur is target)
return step;
/* 将 cur 的相邻节点加入队列 */
for (Node x : cur.adj())
if (x not in visited) {
q.offer(x);
visited.add(x);
}
}
/* 划重点:更新步数在这里 */
step++;
}
}
2.二叉树的最小高度(套模板)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
//采用广度搜索,首先先要一个队列
Queue<TreeNode> q = new LinkedList<>();
if(root == null){
return 0;
}
q.offer(root);//添加进去
//因为root本身就是一层,depth初始化为1
int depth = 1;
//开始循环队列,知道队列为空
while(!q.isEmpty()){
int sz = q.size();//1.首先求出当前队列长度
//2.然后根据当前队列向后扩展,也就是他们的子树
for(int i = 0;i < sz;i++){
//3.弹出队头
TreeNode cur = q.poll();
//4.判断是否到达终点,也就是树是否已经遍历完
if(cur.left == null && cur.right == null){
return depth;//返回结果
}
//5.到达这里说明树还没有遍历完毕
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
}
depth++;//上面的for相当于遍历完一层了
}
return depth;
}
}