Leetcode of depth-first search (DFS) Thematic -733. Image rendering (Flood Fill)

Leetcode of depth-first search (DFS) Thematic -733. Image rendering (Flood Fill)

Problem-solving depth-first search details, click


 

There is a picture representation of a two-dimensional array of integers, each integer represents a pixel value of the size of the picture, the value of 0 to 65535 between. 

Give you a coordinate (sr, sc) represents the start of image rendering pixel values (row, column) and a new color values newColor, allow you to re-color this image. 

In order to complete the work of color, from the initial coordinates, recording four directions initial coordinate values of the initial coordinates of a pixel connected to the same pixel, and then re-recording pixels qualifying them with the four directions corresponding to four the same is connected to the pixel value of the pixel coordinates of the initial point, ......, the process is repeated. The color of all recorded pixel color values to the new values. 

Finally, return the image through color rendering. 

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 ]] 
Analysis: 
in the middle of the image, (coordinates (SR, SC) = (1,1 )), 
in the path of all eligible color pixels have been changed to 2. 
Note that the pixel does not change to the lower right corner 2, 
because it is not a pixel in the vertical and horizontal four directions connected to the initial point. 
Note: 

Image and Image [ 0] of length in the range [1, 50] Inside. 
The original point analysis satisfies 0 <= sr <image.length and 0 <= SC <Image [0 ] .length. 
image [i] [j] and the color value newColor shown in the range [ 0, 65535] within.

Simple difficulty, even VIS arrays do not have a direct search for the four directions on the line.

 

AC Code:

class Solution {
    int dirx[] = {0,0,1,-1};
    int diry[] = {1,-1,0,0};
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if(image==null || image.length == 0) return image;
        if(image[sr][sc]==newColor) return image;
        dfs(image,sr,sc,newColor,image[sr][sc]);
        return image;
    }
    public void dfs(int[][] image,int sr,int sc,int newColor,int value){
        image[sr][sc] = newColor;
        
        for(int i=0;i<4;i++){
            int xx = sr + dirx[i];
            int yy = sc + diry[i];
            if(xx>=0 && yy>=0 && xx<image.length && yy<image[0].length && image[xx][yy]==value){
                dfs(image,xx,yy,newColor,value);
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11361373.html