[LeetCode] 733. Flood Fill

Image rendering. There is a picture represented by a two-dimensional integer array, and each integer represents the pixel value of the picture, with a value between 0 and 65535. Give you a coordinate (sr, sc) that represents the pixel value (row, column) at which the image is rendered and a new color value newColor, allowing you to recolor the image. In order to complete the coloring work, starting from the initial coordinates, record the connected pixel points with the same pixel value as the initial coordinates in the up, down, left, and right directions of the initial coordinates, and then record the corresponding pixels in these four directions corresponding to the four corresponding pixels. Connected pixels with the same pixel value in the direction as the initial coordinates, ..., repeat the process. Change the color value of all recorded pixels to the new color value. Finally, return to the rendered image. example,

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.

This question is very similar to the previous 695 and 547. The title gives the starting position and the color newColor that needs to be updated. The idea is to use DFS to determine whether the color needs to be updated on the coordinates of the four directions. Note that if it exceeds the input range, or has been dyed, then return directly.

Time O (mn)

Space O (mn)

Java implementation

 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 }

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12717235.html