【Leetcode】733. Flood Fill

class Solution(object):

    def floodFill(self, image, sr, sc, newColor):

        """

        :type image: List[List[int]]

        :type sr: int

        :type sc: int

        :type newColor: int

        :rtype: List[List[int]]

        """

        rows, columne, origCol = len(image), len(image[0]), image[sr][sc]

        def traverse(row, col):

            if 0<=row<rows and 0<=col<columne and image[row][col]==origCol:

                image[row][col]=newColor

            else:

                return

            [traverse(row+x, col+y) for (x,y) in((0,1), (0,-1), (1,0), (-1,0))]

        if image[sr][sc]!=newColor:

            traverse(sr, sc)

        return image

1 用DFS来实现,DFS一般是用递归方法

2 从starting point开始,递归遍历这个起点上下左右的各个点,再以那些点为起点,看它周围上下左右的点,这就是DFS搜索

3 对于每一个递归函数来说,也就是对于每一个点来说,我们只需要判断它是不是在row和colume的正确范围内,还有判断这个点的颜色是不是和starting point的颜色一样。如果不一样,直接返回。如果上述条件都满足,则将新的color置换掉之前的color

4 再递归调用判断4-directional上面的四个点

5 return的时候,也可以直接写个return,不return任何值

6 特殊情况:如果新颜色和starting point的颜色一样的话,就直接返回image


1 我这种方法太耗费空间了,多建立了一个matrix;因为要把和最初始颜色一样的重置,所以只要保留初始点color就行,然后后面的都和它比较


1 注意如果起始点color和newColor是一样的话,就不需要调用dfs了,不然就进入死循环了,因为会不停得来回调用


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容