// 计算从起点 start 到终点 target 的最近距离
int BFS(Node start, Node target) {
Queue<Node> q; // 核心数据结构
Set<Node> visited; // 避免走回头路
q.offer(start); // 将起点加入队列
visited.add(start);
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);
}
}
}
}
// 如果走到这里,说明在图中没有找到目标节点
}
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
//leetcode submit region begin(Prohibit modification and deletion)
import java.util.LinkedList;
import java.util.Queue;
//
//*
// * 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) {
//bfs广度优先,得出的肯定是最小深度
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int step = 1;
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
if (cur.left == null && cur.right == null) {
return step;
}
if (cur.left != null) {
q.offer(cur.left);
}
if (cur.right != null) {
q.offer(cur.right);
}
}
step++;
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
打开转盘锁,采用双向bfs
import java.util.*;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> q1 = new HashSet<>();
Set<String> q2 = new HashSet<>();
Set<String> dead = new HashSet<>(Arrays.asList(deadends));
Set<String> visited = new HashSet<>();
q1.add("0000");
q2.add(target);
int step = 0;
while (!q1.isEmpty() && !q2.isEmpty()) {
Set<String> temp = new HashSet<>();
for (String current : q1) {
if (dead.contains(current)) {
continue;
}
if (q2.contains(current)) {
return step;
}
visited.add(current);
for (int i = 0; i < 4; i++) {
String upString = up(current, i);
if (!visited.contains(upString)) {
temp.add(upString);
}
String downString = down(current, i);
if (!visited.contains(downString)) {
temp.add(downString);
}
}
}
q1 = q2;
q2 = temp;
step++;
}
return -1;
}
public String up(String source, int j) {
char ch[] = source.toCharArray();
if (ch[j] == '9') {
ch[j] = '0';
}
else {
ch[j] += 1;
}
return new String(ch);
}
public String down(String source, int j) {
char ch[] = source.toCharArray();
if (ch[j] == '0') {
ch[j] = '9';
}
else {
ch[j] -= 1;
}
return new String(ch);
}
}
//leetcode submit region end(Prohibit modification and deletion)