ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

刷题-力扣-面试题 08.10. 颜色填充

2022-03-03 20:01:44  阅读:187  来源: 互联网

标签:面试题 newColor int sr image 08.10 floodFill 力扣 sc


题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/color-fill-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

编写函数,实现许多图片编辑软件都支持的「颜色填充」功能。

待填充的图像用二维数组 image 表示,元素为初始颜色值。初始坐标点的行坐标为 sr 列坐标为 sc。需要填充的新颜色为 newColor 。

「周围区域」是指颜色相同且在上、下、左、右四个方向上存在相连情况的若干元素。

请用新颜色填充初始坐标点的周围区域,并返回填充后的图像。

示例:

输入:
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 ,因为它不属于初始坐标点的周围区域。

提示:

  • image 和 image[0] 的长度均在范围 [1, 50] 内。
  • 初始坐标点 (sr,sc) 满足 0 <= sr < image.length 和 0 <= sc < image[0].length 。
  • image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535] 内。

题目分析

  1. 根据题目描述,将相邻切相同颜色的格子,改变颜色
  2. 广度优先搜索,将相邻区域切颜色相同的位置改变颜色

代码

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        if (newColor == image[sr][sc]) { return image; }
        floodFill(image, sr, sc, newColor, image[sr][sc]);
        return image;
    }

private:
    void floodFill(std::vector<std::vector<int>>& image, int sr, int sc, int newColor, int oldColor) {
        if (sr < 0 || sr >= image.size() || sc < 0 || sc >= image[sr].size()) { return; }
        if (image[sr][sc] == newColor) { return; }
        if (image[sr][sc] == oldColor) {
            image[sr][sc] = newColor;
            floodFill(image, sr - 1, sc, newColor, oldColor);
            floodFill(image, sr + 1, sc, newColor, oldColor);
            floodFill(image, sr, sc - 1, newColor, oldColor);
            floodFill(image, sr, sc + 1, newColor, oldColor);
        }
        return;
    }

};

标签:面试题,newColor,int,sr,image,08.10,floodFill,力扣,sc
来源: https://www.cnblogs.com/HanYG/p/15961526.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有