算法练习-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]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值