Problem
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:
The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in imagei and newColor will be an integer in [0, 65535].
class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { if (image[sr][sc] == newColor) return image; dfs(image, sr, sc, image[sr][sc], newColor); return image; } public void dfs(int[][] image, int i, int j, int pre, int cur) { if (i >= 0 && i < image.length && j >= 0 && j < image[0].length && image[i][j] == pre) { image[i][j] = cur; dfs(image, i-1, j, pre, cur); dfs(image, i+1, j, pre, cur); dfs(image, i, j-1, pre, cur); dfs(image, i, j+1, pre, cur); } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72216.html
摘要:原文链接最近在知乎上看到一个问题,随机生成指定面积单连通区域,感觉还挺有意思的,于是整理一下写一篇新文章。问题阐述如下图所示,在的区域中,随机生成面积为的单连通区域,该随机包括位置随机以及形状随机。 原文链接:https://xcoder.in/2018/04/01/random-connected-area/ 最近在知乎上看到一个问题,「随机生成指定面积单连通区域?」,感觉还挺有意...
摘要:作为智能全球防御体系产品矩阵之一的全球清洗,针对云内资源提供防御,防护覆盖东南亚所有地区,延时低至。亚太高防部署简单,购买后只需将高防绑定到需要防护的云产品上即可生效。具有实时防御低延时高可靠大防护的特点。支持弹性防护容量最大可至后付费。作为UCloud智能全球DDoS防御体系产品矩阵之一的全球清洗UanycastClean,针对UCloud云内资源提供DDoS防御,防护覆盖东南亚所有地区,...
摘要:空间复杂度方法是否为最大的幂的约数思路最大的的幂为,判断是否是的约数即可。复杂度时间复杂度,一个整数统计二进制的复杂度,最坏的情况下是。 大厂算法面试之leetcode精讲9.位运算视频教程(高效学习):点击学习目录:1.开篇介绍2.时间空间复杂度3.动态规划4.贪心5.二分查找6.深度优先&广度优先7.双指针...
阅读 3355·2021-10-11 11:06
阅读 2162·2019-08-29 11:10
阅读 1909·2019-08-26 18:18
阅读 3217·2019-08-26 13:34
阅读 1541·2019-08-23 16:45
阅读 1019·2019-08-23 16:29
阅读 2770·2019-08-23 13:11
阅读 3188·2019-08-23 12:58