[LeetCode] 733. Flood Fill

图像渲染。有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。最后返回经过上色渲染后的图像。例子,

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.

这一题跟之前的695和547很类似。题目给了起始位置和需要更新的颜色newColor,思路是用DFS判断四个方向的坐标上是否需要被更新颜色。注意如果超出input范围,或者已经被染色过了则直接return。

时间O(mn)

空间O(mn)

Java实现

 1 class Solution {
 2     public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
 3         // corner case
 4         if (image[sr][sc] == newColor) {
 5             return image;
 6         }
 7 
 8         // normal case
 9         helper(image, sr, sc, image[sr][sc], newColor);
10         return image;
11     }
12 
13     private void helper(int[][] image, int sr, int sc, int color, int newColor) {
14         if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != color) {
15             return;
16         }
17         image[sr][sc] = newColor;
18         helper(image, sr + 1, sc, color, newColor);
19         helper(image, sr - 1, sc, color, newColor);
20         helper(image, sr, sc + 1, color, newColor);
21         helper(image, sr, sc - 1, color, newColor);
22     }
23 }

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12717235.html