Flood Fill

题目
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.

答案

class Solution {
    int[][] dirs = {{0, -1},{-1, 0},{0, 1},{1, 0}};
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int[][] new_image = new int[image.length][image[0].length];
        for(int i = 0; i < image.length; i++) {
            for(int j = 0; j < image[0].length; j++) {
                new_image[i][j] = image[i][j];
            }
        }
        recur(image, new_image, sr, sc, newColor);
        return new_image;
    }
    
    private void recur(int[][] image, int[][] new_image, int sr, int sc, int newColor) {
        int oldColor = image[sr][sc];
        new_image[sr][sc] = newColor;
        // visited
        image[sr][sc] = -1;
        for(int i = 0; i < 4; i++) {
            int sr2 = sr + dirs[i][0];
            int sc2 = sc + dirs[i][1];
            if(sr2 >= 0 && sr2 < image.length && sc2 >= 0 && sc2 < image[0].length && image[sr2][sc2] == oldColor) {
                recur(image, new_image, sr2, sc2, newColor);
            }
        }        
    }
}

你可能感兴趣的:(Flood Fill)