Leetcode 733. Flood Fill

285 篇文章 2 订阅
138 篇文章 0 订阅

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值