733. 图像渲染

image.png

递归解法

执行用时:84 ms, 在所有 JavaScript 提交中击败了94.96% 的用户 内存消耗:39.9 MB, 在所有 JavaScript 提交中击败了56.30% 的用户

  1. var floodFill = function (image, sr, sc, newColor) {
  2. // 如果目标颜色与图象原颜色相等,则直接返回,否则出现死循环
  3. if (newColor === image[sr][sc]) return image;
  4. floodFillRecursion(image, sr, sc, newColor, image[sr][sc]);
  5. return image;
  6. };
  7. var floodFillRecursion = function (image, sr, sc, newColor, oldColor) {
  8. // 坐标越界判断
  9. if (!(sr >= 0 && sr < image.length && sc >= 0 && sc < image[0].length)) {
  10. return;
  11. }
  12. // 是否为目标颜色,如果不是,跳出递归
  13. if (image[sr][sc] === oldColor) {
  14. image[sr][sc] = newColor;
  15. } else {
  16. return;
  17. }
  18. for (let d of dire) {
  19. // 递归调用上下左右
  20. floodFillRecursion(image, sr + d[0], sc + d[1], newColor, oldColor);
  21. }
  22. }
  23. // 定义上下左右方向
  24. var dire = [
  25. [0, 1],
  26. [0, -1],
  27. [1, 0],
  28. [-1, 0]
  29. ]