leetcode 20天算法计划day7

733. 图像渲染

733. 图像渲染 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/flood-fill/

思路:

1.广度优先搜索

(1)从一个格子出发,将其所对应的下表元组加入一个空列表,并将其颜色修改

(2)按照一个固定的顺序遍历其上下左右的所有格子

(3)如果格子内和初始格子的值相同,则将其格子对应的下表元组加入列表,并修改它对应的值为目标值

(4)每次从列表中取出一个来作为当前格子,反复操作直到列表为空为止。

(5)列表弹出最好用collections模块当中的deque结构,实现先进先出的队列结构

2.深度优先搜索

(1)从一个格子出发,将其颜色修改

(2)向某一个方向一直前进,直到达到格子边界

(3)过程中如果遇到了和初始颜色相同的格子,则将其颜色改变,否则继续前进

(4)可以设置一个函数来执行上述过程

代码:

1.广度:

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        nowColor = image[sr][sc]
        if nowColor == newColor:
            return image
        
        m, n = len(image), len(image[0]) #获取行列数
        que = collections.deque([(sr, sc)])
        image[sr][sc] = newColor
        while que:
            x, y = que.popleft()
            for mx, ny in [(x+1, y), (x-1, y), (x,y-1), (x, y+1)]:
                if 0 <= mx < m and 0 <= ny < n and image[mx][ny] == nowColor :
                    que.append((mx, ny))    
                    image[mx][ny] = newColor
                    print(mx,ny)
        return image

2.深度:

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        m, n = len(image), len(image[0])
        nowColor = image[sr][sc]
        
        def DFS(x, y):
            if image[x][y] == nowColor:
                image[x][y] = newColor
                for mx, ny in[(x+1, y), (x-1, y), (x, y-1), (x, y+1)]:
                    if 0<=mx<m and 0<=ny<n and image[mx][ny] == nowColor:
                        DFS(mx, ny)
        
        if nowColor != newColor:
            DFS(sr, sc)
        return image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值