LeetCode 算法入门 — 图像渲染

351 阅读3分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

图像渲染

原题地址

有一幅以 m x n 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。

你也被给予三个整数 srscnewColor。你应该从像素 image[sr][sc] 开始对图像进行 上色填充

为了完成 上色工作 ,从初始像素开始,记录初始坐标的 上下左右四个方向上 像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应 四个方向上 像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为 newColor 。

最后返回 经过上色渲染后的图像 。

示例 1:

输入: image = [[1,1,1],[1,1,0],[1,0,1]],sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析: 在图像的正中间,(坐标(sr,sc)=(1,1)),在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,因为它不是在上下左右四个方向上与初始点相连的像素点。

示例 2:

输入: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
输出: [[2,2,2],[2,2,2]]

思路分析

方法一

  1. 使用深度优先遍历;
  2. 逐步给 img 中的 (sr, sc) 周边即上下左右的部分进行 「上色」;
  3. 定义 dfs 方法进行遍历,做边界判断和上色要求的判断。

方法二

  1. 定义数组 result 来存储需要上色的点;
  2. result 不为空时,需要继续上色,直到都上完为止。

AC 代码

方法一

/**
 * @param {number[][]} image
 * @param {number} sr
 * @param {number} sc
 * @param {number} newColor
 * @return {number[][]}
 */
const floodFill = function (image, sr, sc, newColor) {
    dfs(image, sr, sc, newColor, image[sr][sc])
    return image
};

const dfs = (image, sr, sc, newColor, color) => {
    // 越界判断
    if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) return
    // 不满足上色要求, 或已经上色过
    if (image[sr][sc] != color || image[sr][sc] == newColor) return;
    // 上色
    image[sr][sc] = newColor

    dfs(image, sr - 1, sc, newColor, color) // 左
    dfs(image, sr, sc + 1, newColor, color) // 下
    dfs(image, sr + 1, sc, newColor, color) // 右
    dfs(image, sr, sc - 1, newColor, color) // 上
}

结果:

  • 执行结果: 通过
  • 执行用时:68 ms, 在所有 JavaScript 提交中击败了87.11%的用户
  • 内存消耗:42.8 MB, 在所有 JavaScript 提交中击败了51.46%的用户
  • 通过测试用例:277 / 277

方法二

/**
 * @param {number[][]} image
 * @param {number} sr
 * @param {number} sc
 * @param {number} newColor
 * @return {number[][]}
 */
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 result = [[sr, sc]];

    while (result.length) {
        const [i, j] = result.shift();
        image[i][j] = newColor;

        if (i - 1 >= 0 && image[i - 1][j] == oldColor) result.push([i - 1, j]);
        if (i + 1 < m && image[i + 1][j] == oldColor) result.push([i + 1, j]);
        if (j - 1 >= 0 && image[i][j - 1] == oldColor) result.push([i, j - 1]);
        if (j + 1 < n && image[i][j + 1] == oldColor) result.push([i, j + 1]);
    }

    return image;
};

结果:

  • 执行结果: 通过
  • 执行用时:64 ms, 在所有 JavaScript 提交中击败了95.29%的用户
  • 内存消耗:43.1 MB, 在所有 JavaScript 提交中击败了21.60%的用户
  • 通过测试用例:277 / 277

END