图像填充问题:给定一个二维网格和一个起始像素点,将与起始像素点相邻且颜色相同的像素点填充成目标颜色。
我们分别使用深度优先搜索(DFS)和广度优先搜索(BFS)来解决图像填充问题,即将与起始像素点相邻且颜色相同的像素点填充成目标颜色。
首先,我们需要定义一个二维网格的表示方法。我们可以使用二维列表来表示网格。
深度优先搜索(DFS)方法:
def dfs_fill(image, sr, sc, newColor):"""使用深度优先搜索(DFS)来填充图像中相邻像素点的颜色。Parameters:image (list): 二维网格表示的图像。sr (int): 起始像素点的行坐标。sc (int): 起始像素点的列坐标。newColor: 目标颜色。Returns:list: 填充后的图像。"""def dfs(r, c, color):if r < 0 or r >= len(image) or c < 0 or c >= len(image[0]) or image[r][c] != color:returnimage[r][c] = newColordfs(r + 1, c, color)dfs(r - 1, c, color)dfs(r, c + 1, color)dfs(r, c - 1, color)color = image[sr][sc]if color != newColor:dfs(sr, sc, color)return image# 示例二维网格表示的图像
image = [[1, 1, 1],[1, 1, 0],[1, 0, 1]
]
# 起始像素点的坐标和目标颜色
sr, sc, newColor = 1, 1, 2# 填充图像
filled_image = dfs_fill(image, sr, sc, newColor)
print("填充后的图像(使用DFS):", filled_image)
广度优先搜索(BFS)方法:
from collections import dequedef bfs_fill(image, sr, sc, newColor):"""使用广度优先搜索(BFS)来填充图像中相邻像素点的颜色。Parameters:image (list): 二维网格表示的图像。sr (int): 起始像素点的行坐标。sc (int): 起始像素点的列坐标。newColor: 目标颜色。Returns:list: 填充后的图像。"""color = image[sr][sc]if color == newColor:return imagequeue = deque([(sr, sc)])directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]while queue:r, c = queue.popleft()image[r][c] = newColorfor dr, dc in directions:nr, nc = r + dr, c + dcif 0 <= nr < len(image) and 0 <= nc < len(image[0]) and image[nr][nc] == color:queue.append((nr, nc))return image# 示例二维网格表示的图像
image = [[1, 1, 1],[1, 1, 0],[1, 0, 1]
]
# 起始像素点的坐标和目标颜色
sr, sc, newColor = 1, 1, 2# 填充图像
filled_image = bfs_fill(image, sr, sc, newColor)
print("填充后的图像(使用BFS):", filled_image)
上述代码分别使用了深度优先搜索(DFS)和广度优先搜索(BFS)来填充图像中与起始像素点相邻且颜色相同的像素点。填充过程中,我们使用递归的方式来实现深度优先搜索,使用队列和迭代的方式来实现广度优先搜索。