深度优先搜索(DFS)和广度优先搜索(BFS)

DFS:深度优先搜索,优先深度来遍历,获取所需要的数值。针对图和树这样的数据结构。对每一个可能的分支路径深入到不能再深入为止,每个结点只能访问一次。
BFS:广度优先搜索,盲目搜寻法,不考虑结点所在的可能位置,彻底搜索这张图,直到找到结点为止。当所有结点被访问,算法终止。

题型一:

图像渲染

image.png
BFS:

  1. const floodFill = (image, sr, sc, newColor) => {
  2. const m = image.length;
  3. const n = image[0].length;
  4. const oldColor = image[sr][sc];//记录旧颜色
  5. if (oldColor == newColor) return image;//如果上色颜色不变,则返回原图
  6. const queue = [[sr, sc]];
  7. while (queue.length) {
  8. const [i, j] = queue.shift();
  9. //将需要染色的坐标传递出来
  10. image[i][j] = newColor;
  11. //将该坐标染色
  12. if (i - 1 >= 0 && image[i - 1][j] == oldColor) queue.push([i - 1, j]);
  13. if (i + 1 < m && image[i + 1][j] == oldColor) queue.push([i + 1, j]);
  14. if (j - 1 >= 0 && image[i][j - 1] == oldColor) queue.push([i, j - 1]);
  15. if (j + 1 < n && image[i][j + 1] == oldColor) queue.push([i, j + 1]);
  16. //上面四行判断是否周边有相同的点
  17. }
  18. return image;
  19. };

DFS:

  1. const floodFill = (image, sr, sc, newColor) => {
  2. const m = image.length;
  3. const n = image[0].length;
  4. const oldColor = image[sr][sc];
  5. if (oldColor == newColor) return image;//如果颜色不变,则返回原图
  6. const fill = (i, j) => {
  7. if (i < 0 || i >= m || j < 0 || j >= n || image[i][j] != oldColor) {
  8. return;
  9. }
  10. image[i][j] = newColor;
  11. fill(i - 1, j);
  12. fill(i + 1, j);
  13. fill(i, j - 1);
  14. fill(i, j + 1);
  15. };
  16. fill(sr, sc);
  17. return image;
  18. };