秋招-算法-BFS篇
介绍
BFS 的核心思想就是把一些问题抽象成图,从一个点开始,向四周开始扩散。一般来说,我们写 BFS 算法都是用「队列」这种数据结构,每次将一个节点周围的所有节点加入队列。
BFS 相对 DFS 的最主要的区别是:BFS 找到的路径一定是最短的,但代价就是空间复杂度可能比 DFS 大很多
模板
通过while向下遍历,通过for横向遍历
// 计算从起点 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++;
}
}
例题
111. 二叉树的最小深度
class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
int dep = 1;
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
if (poll.right==null&&poll.left==null){
return dep;
}
if (poll.left!=null)
queue.offer(poll.left);
if (poll.right!=null)
queue.offer(poll.right);
}
dep++;
}
return dep;
}
}
752. 打开转盘锁
class Solution {
public int openLock(String[] deadends, String target) {
if("0000".equals(target)) return 0;
Queue<String> queue = new LinkedList<>();
Set<String> deads = new HashSet<>();
for (String s : deadends) deads.add(s);
queue.offer("0000");
Set<String> visited = new HashSet<>();
visited.add("0000");
int dep = 0;
//纵向寻找
while (!queue.isEmpty()){
int size = queue.size();
//横向寻找所有的可能结果
for (int i = 0; i < size; i++) {
String poll = queue.poll();
if (deads.contains(poll))
continue;
if (target.equals(poll)){
return dep;
}
for (int j = 0; j < poll.length(); j++) {
String up = up(poll, j);
if (!visited.contains(up)) {
queue.offer(up);
visited.add(up);
}
String down = down(poll, j);
if (!visited.contains(down)) {
queue.offer(down);
visited.add(down);
}
}
}
dep++;
}
return -1;
}
private String up(String poll, int pos) {
char[] ch = poll.toCharArray();
if (ch[pos] == '9') {
ch[pos] = '0';
}else{
ch[pos]+=1;
}
return String.valueOf(ch);
}
private String down(String poll, int pos) {
char[] ch = poll.toCharArray();
if (ch[pos] == '0') {
ch[pos] = '9';
}else{
ch[pos]-=1;
}
return String.valueOf(ch);
}
}