BFS DFS

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

题型一:
图像渲染
image.png

BFS:

const floodFill = (image, sr, sc, newColor) => {
  const m = image.length;
  const n = image[0].length;
  const oldColor = image[sr][sc];//记录旧颜色

  if (oldColor == newColor) return image;//如果上色颜色不变,则返回原图

  const queue = [[sr, sc]];

  while (queue.length) {
    const [i, j] = queue.shift();
    //将需要染色的坐标传递出来
    image[i][j] = newColor;
    //将该坐标染色
    if (i - 1 >= 0 && image[i - 1][j] == oldColor) queue.push([i - 1, j]);
    if (i + 1 < m && image[i + 1][j] == oldColor) queue.push([i + 1, j]);
    if (j - 1 >= 0 && image[i][j - 1] == oldColor) queue.push([i, j - 1]);
    if (j + 1 < n && image[i][j + 1] == oldColor) queue.push([i, j + 1]);
    //上面四行判断是否周边有相同的点
  }

  return image;
};

DFS:

const floodFill = (image, sr, sc, newColor) => {
  const m = image.length;
  const n = image[0].length;
  const oldColor = image[sr][sc];
  if (oldColor == newColor) return image;//如果颜色不变,则返回原图

  const fill = (i, j) => {
    if (i < 0 || i >= m || j < 0 || j >= n || image[i][j] != oldColor) {
      return;
    }
    image[i][j] = newColor; 
    fill(i - 1, j);
    fill(i + 1, j);
    fill(i, j - 1);
    fill(i, j + 1);
  };

  fill(sr, sc);
  return image;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值