- DFS(Depth First Search)深度优先搜索
- BFS(Breath First Search)广度优先搜索
就是两种暴力搜索去遍历所有的情况。
走迷宫来理解这两种搜索思想:
- DFS —— 先选择一个方向,然后遇到的每一个岔路,都继续走这个方向,直到此路不通(不通则返回上一个岔路重新选一个方向继续这样走)或走出迷宫。
- BFS —— 遇到岔路,向全部的方向先走一步(一步指遇到下一个岔路为止),每个方向都走完一步后,再从遇到的第一个岔路继续这样走,直到走出迷宫。(有人用水漫金山来形容BFS,还挺形象)
遍历二叉树来理解这两种搜索思想:
- DFS —— 前中后序遍历
- BFS —— 层序遍历
通过解决 leetcode 733. 图像渲染,理解BFS与DFS思想。
【测试示例图示】
DFS
递归实现深度优先搜索
class Solution {
//用来控制向上下左右移动( +dx[i], +dy[i])
int[] dx = {1, 0, 0, -1};
int[] dy = {0, 1, -1, 0};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
// currColor = 当前颜色
int currColor = image[sr][sc];
if (currColor != newColor) {
dfs(image, sr, sc, currColor, newColor);
}
return image;
}
public void dfs(int[][] image, int x, int y, int currcolor, int newColor) {
//满足条件
if (image[x][y] == currcolor) {
image[x][y] = newColor;
// 遍历上下左右四个方向
for (int i = 0; i < 4; i++) {
int mx = x + dx[i], my = y + dy[i];
// 保证(mx, my)在矩阵范围内
if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {
// 递归
dfs(image, mx, my, currcolor, newColor);
}
}
}
}
}
BFS
队列实现广度优先搜索
class Solution {
// 用来控制向上下左右移动( +dx[i], +dy[i])
int[] dx = {1, 0, 0, -1};
int[] dy = {0, 1, -1, 0};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
// currColor = 当前颜色
int currColor = image[sr][sc];
// 与更新色相同就直接返回
if (currColor == newColor) {
return image;
}
// n, m为矩阵边界
int n = image.length, m = image[0].length;
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(new int[]{sr, sc});
image[sr][sc] = newColor;
// 循环直到队列为空
while (!queue.isEmpty()) {
// 出队列
int[] cell = queue.poll();
int x = cell[0], y = cell[1];
// 遍历上下左右四个方向
for (int i = 0; i < 4; i++) {
int mx = x + dx[i], my = y + dy[i];
// 0<= mx,my <=n/m 保证在矩阵范围内
if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {
// 加入队列并更新颜色
queue.offer(new int[]{mx, my});
image[mx][my] = newColor;
}
}
}
return image;
}
}
感谢阅读 😉😉