Leetcode733:图像渲染(广度遍历解法)

题目:
有一幅以 m x n 的二维整数数组示意的图画 image ,其中 imagei 示意该图画的像素值大小。

...

上一篇文章用深度遍历的办法解了一下这道题,起初感觉应该再用深度遍历的办法解决一下,防止本人只学到套路没懂得思维。

明天给一个广度遍历的解法

答题:

var floodFill = function(image, sr, sc, newColor) {    let lineLen=image.length, rowLine=image[0].length;    let oldColor=image[sr][sc];    //依据题意,当(sr,sc)与newcolor一样时则不须要扭转。    if(oldColor==newColor) return image;        //BFS;    while(queue.length){        const [line, row]=queue.shift();        image[line][row]=newColor;        if(line>0&&image[line-1][row]==oldColor)queue.push([line-1,row]);        if(line<lineLen-1&&image[line+1][row]==oldColor)queue.push([line+1,row]);        if(row>0&&image[line][row-1]==oldColor)queue.push([line,row-1]);        if(row<rowLine-1&&image[line][row+1]==oldColor)queue.push([line,row+1]);        }    return image;};

从实现思路来看,深度遍历咱们要一条路走到黑,广度遍历则要求咱们先找到下一层的指标点。实现的形式前者用递归,后者利用数组来执行队列操作。两者具体的区别今天好好写一下~