Leetcode 733. Flood Fill

这篇博客介绍了一种使用深度优先搜索(DFS)算法解决图像填充问题的方法。给定一个网格图像和起始像素坐标,你需要将所有同色相邻像素替换为指定颜色,展示了如何通过递归实现 floodFill 函数来完成操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].

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), and so on. Replace the color of all of the aforementioned pixels with color.

Return the modified image after performing the flood fill.

Algorithm

DFS. Note when starting pixel is same as the color.

Code

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        if image[sr][sc] == color:
            return image
        
        def floodfill(sr, sc, rr, cc, scolor, color):
            if sr < 0 or sr >= rr or sc < 0 or sc >= cc or image[sr][sc] != scolor:
                return
            image[sr][sc] = color
            floodfill(sr-1, sc, rr, cc, scolor, color)
            floodfill(sr+1, sc, rr, cc, scolor, color)
            floodfill(sr, sc-1, rr, cc, scolor, color)
            floodfill(sr, sc+1, rr, cc, scolor, color)       
        
        rr = len(image)
        cc = len(image[0])
        floodfill(sr, sc, rr, cc, image[sr][sc], color)
        return image
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值