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

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;};
