算法练习-LeetCoe 733. Flood Fill

题目地址:https://leetcode.com/problems/flood-fill/description/

解题思路:深度优先搜索

code(java):

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
    int oldColor = image[sr][sc];
    if (oldColor == newColor) {
        return image;
    }
    fill(image, sr, sc, oldColor, newColor);
    return image;
}

private void fill(int[][] image, int row, int col, int oldColor, int newColor) {
    if (row < 0 || row >= image.length || col < 0 || col >= image[0].length || image[row][col] != oldColor) {
        return;
    }
    image[row][col] = newColor;
    fill(image, row - 1, col, oldColor, newColor);
    fill(image, row + 1, col, oldColor, newColor);
    fill(image, row, col - 1, oldColor, newColor);
    fill(image, row, col + 1, oldColor, newColor);
}

This method takes a 2D integer array image, two integers sr and sc, and an integer newColor as input, and returns the modified image after performing the flood fill. It first checks if the oldColor at the starting pixel image[sr][sc] is equal to the newColor, and returns the image if they are equal. Otherwise, it calls a helper method fill to perform the flood fill. The fill method performs a depth-first search on the image starting from the pixel (row, col), and replaces the oldColor with the newColor at each visited pixel. It recursively calls itself on the neighboring pixels of the current pixel that have the same oldColor.

For example, if image is the following 2D integer array:

[[1,1,1],
 [1,1,0],
 [1,0,1]]

And we call floodFill(image, 1, 1, 2), the method will perform the flood fill starting from the pixel (1, 1) with oldColor 1 and newColor 2. The resulting image will be:

[[2,2,2],
 [2,2,0],
 [2,0,1]]

猜你喜欢

转载自blog.csdn.net/qq_41758969/article/details/129189755