LeetCode-Flood Fill

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89186736

Description:
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 image[i][j] and newColor will be an integer in [0, 65535].

题意:给定一个二维数组表示的像素值image、起始的位置sr和sc、新的填充颜色newColor;现在要求从起始位置开始,将所有与其相邻位置(定义相邻位置为上下左右四个方向)处的像素值设置为newColor(要求相邻位置处的像素值与起始位置处的相同),对相邻位置更新过颜色值的位置进行同样的处理(但是要求颜色值是与sr,sc处的相同);

解法:对sr,sc处相邻位置处理后,还需要对相邻位置的相邻位置处理,因此,可以利用深度遍历的算法直到某个位置相邻所有位置都已经处理;

Java
class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        boolean[][] visited = new boolean[image.length][image[sr].length];
        fill(image, sr, sc, image[sr][sc], newColor, visited);
        return image;
    }
    
    private void fill(int[][] image, int row, int col, int oldColor, 
                      int newColor, boolean[][] visited) {
        if (visited[row][col] || image[row][col] != oldColor) {
            return;
        }
        image[row][col] = newColor;
        visited[row][col] = true;
        if (row + 1 < image.length) {
            fill(image, row + 1, col, oldColor, newColor, visited);
        }
        if (row - 1 >= 0) {
            fill(image, row - 1, col, oldColor, newColor, visited);
        }
        if (col + 1 < image[row].length) {
            fill(image, row, col + 1, oldColor, newColor, visited);
        }
        if (col - 1 >= 0) {
            fill(image, row, col - 1, oldColor, newColor, visited);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/89186736