广度优先搜索BFS
特点
- 解决两类问题:从A出发是否存在路径到达B点;从A出发到达B点的最短路径
- 不考虑结果的可能位置,彻底的搜索整张图,直到找到结果为止
- 通过队列(queue)来实现
最简单的应用:二叉树的层次遍历
LeetCode102:给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList();
if(root == null)
return res;
LinkedList<TreeNode> queue1 = new LinkedList();
LinkedList<TreeNode> queue2 = new LinkedList();
queue1.offer(root);
while(!queue1.isEmpty()) {
List<Integer> temp = new ArrayList();
while(!queue1.isEmpty()) {
TreeNode cur = queue1.pollFirst();
temp.add(cur.val);
if(cur.left != null)
queue2.offer(cur.left);
if(cur.right != null)
queue2.offer(cur.right);
}
res.add(temp);
LinkedList<TreeNode> backup = queue1;
queue1 = queue2;
queue2 = backup;
}
return res;
}
}
延伸:网格中的最短路径
给你一个 m * n 的网格,其中每个单元格不是 0(空)就是 1(障碍物)。每一步,您都可以在空白单元格中上、下、左、右移动。如果您 最多 可以消除 k 个障碍物,请找出从左上角 (0, 0) 到右下角 (m-1, n-1) 的最短路径,并返回通过该路径所需的步数。如果找不到这样的路径,则返回 -1。
示例 1:
输入:
grid =
[[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]],
k = 1
输出:6
解释:
不消除任何障碍的最短路径是 10。
消除位置 (3,2) 处的障碍后,最短路径是 6 。该路径是 (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
class Solution {
public int shortestPath(int[][] grid, int k) {
int[][] dir = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int m = grid.length, n = grid[0].length;
Queue<int[]> q = new LinkedList<>();
boolean[][][] visited = new boolean[40][40][40 * 40];
// 记录到达(x,y)需要的最小消除次数,用于剪枝
int[][] minK = new int[m][n];
for (int i = 0; i < m; i++) {
Arrays.fill(minK[i], 160);
}
visited[0][0][grid[0][0] == 0 ? 0 : 1] = true;
minK[0][0] = grid[0][0] == 0 ? 0 : 1;
q.offer(new int[]{0, 0, grid[0][0] == 0 ? 0 : 1});
int cnt = 0;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
int[] cur = q.poll();
int x = cur[0], y = cur[1], z = cur[2];
// 到达终点
if (x == m - 1 && y == n - 1) {
return cnt;
}
for (int[] d : dir) {
int nx = x + d[0], ny = y + d[1];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) {
continue;
}
int num = grid[nx][ny];
// 被访问过 或者 消除次数到达上限 或者 存在到达(nx,ny)且消除次数更少的路径
if (visited[nx][ny][num + z] || num + z > k || num + z >= minK[nx][ny]) {
continue;
}
minK[nx][ny] = num + z;
q.offer(new int[]{nx, ny, num + z});
}
}
cnt++;
}
return -1;
}
}