DFS、BFS遍历算法模板
本文最后更新于 123 天前,如有失效请评论区留言。

题源:图像渲染

DFS解法:

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        target = image[sr][sc]
        if target == color: return image
        vis = {(sr, sc)}
        def dfs(x, y):
            image[x][y] = color
            for nx, ny in zip((x, x, x+1, x-1), (y+1, y-1, y, y)):
                if 0<=nx<len(image) and 0<=ny<len(image[0]) and image[nx][ny]==target and (nx, ny) not in vis:
                    vis.add((nx, ny))
                    dfs(nx, ny)
        dfs(sr, sc)
        return image

BFS解法:

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        if color == image[sr][sc]:   return image
        q = deque()
        q.append((sr, sc))
        vis = {(sr, sc)}
        target = image[sr][sc]
        while q:
            x, y  = q.popleft()
            image[x][y] = color
            for nx, ny in zip((x, x, x+1, x-1), (y+1, y-1, y, y)):
                if 0 <= nx < len(image) and 0 <= ny < len(image[0]) and image[nx][ny] == target and (nx, ny) not in vis:
                    vis.add((nx, ny))
                    q.append((nx, ny))
        return image
版权声明:除特殊说明,博客文章均为大块肌原创,依据CC BY-SA 4.0许可证进行授权,转载请附上出处链接及本声明。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇