【leetcode 面试题 08.10. 颜色填充】Python解题思路

颜色填充。编写函数,实现许多图片编辑软件都支持的“颜色填充”功能。给定一个屏幕(以二维数组表示,元素为颜色值)、一个点和一个新的颜色值,将新颜色值填入这个点的周围区域,直到原来的颜色值全都改变。

解题思路:从指定点出发dfs,改变值,记录访问状态

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        def dfs(visited,image,sr,sc):
            visited[sr][sc]=1
            image[sr][sc]=newColor

            direct=[[0,1],[0,-1],[1,0],[-1,0]]
            for x,y in direct:
                new_x=sr+x 
                new_y=sc+y
                if new_x >=0 and new_x<m and new_y >=0 and new_y<n and visited[new_x][new_y]==0 and image[new_x][new_y]==select:
                    visited[new_x][new_y]=1
                    image[new_x][new_y]=newColor
                    dfs(visited,image,new_x,new_y)

        m=len(image)
        n=len(image[0])
        visited=[[0]*n for _ in range(m)]
        select=image[sr][sc]
        dfs(visited,image,sr,sc)
        return image

你可能感兴趣的:(leetcode,python,leetcode,dfs)