python-leetcode-733. 图像渲染

733. 图像渲染 - 力扣(LeetCode)

这个问题可以用 深度优先搜索(DFS)广度优先搜索(BFS) 来解决。
核心思想是从 image[sr][sc] 开始,遍历相邻的像素点,并将它们的颜色更新为 color,直到没有相同颜色的相邻像素。

代码实现 (DFS)

from typing import List

def floodFill(image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
    rows, cols = len(image), len(image[0])
    original_color = image[sr][sc]

    if original_color == color:
        return image  # 颜色相同,无需填充

    def dfs(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or image[r][c] != original_color:
            return
        image[r][c] = color  # 进行染色
        for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:  # 遍历四个方向
            dfs(r + dr, c + dc)

    dfs(sr, sc)
    return image

代码实现 (BFS)

from collections import deque
from typing import List

def floodFill(image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
    rows, cols = len(image), len(image[0])
    original_color = image[sr][sc]

    if original_color == color:
        return image  # 颜色相同,无需填充

    queue = deque([(sr, sc)])
    while queue:
        r, c = queue.popleft()
        if 0 <= r < rows and 0 <= c < cols and image[r][c] == original_color:
            image[r][c] = color  # 进行染色
            for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:  # 遍历四个方向
                queue.append((r + dr, c + dc))

    return image

复杂度分析:

  • 时间复杂度:O(m * n),最坏情况下所有像素都需要遍历一次。

  • 空间复杂度

    • DFS 最坏情况递归栈深度为 O(m * n)(完全填充情况)。

    • BFS 需要 O(m * n) 的队列存储空间。

DFS 适用于小图像,BFS 更适合大图像,避免递归栈溢出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值