题目
编写函数,实现许多图片编辑软件都支持的「颜色填充」功能。
待填充的图像用二维数组 image 表示,元素为初始颜色值。初始坐标点的行坐标为 sr 列坐标为 sc。需要填充的新颜色为 newColor 。
「周围区域」是指颜色相同且在上、下、左、右四个方向上存在相连情况的若干元素。
请用新颜色填充初始坐标点的周围区域,并返回填充后的图像。
示例
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出:[[2,2,2],[2,2,0],[2,0,1]]
解释:
初始坐标点位于图像的正中间,坐标 (sr,sc)=(1,1) 。
初始坐标点周围区域上所有符合条件的像素点的颜色都被更改成 2 。
注意,右下角的像素没有更改为 2 ,因为它不属于初始坐标点的周围区域。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/color-fill-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:BFS
Java实现
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int[] directions = new int[]{-1, 0, 1, 0, -1};
int row = image.length, col = image[0].length;
Queue<int[]> q = new LinkedList<>();
int pre = image[sr][sc];
if (pre == newColor) return image;
image[sr][sc] = newColor;
q.offer(new int[]{sr, sc});
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
int[] cur = q.poll();
for (int j = 0; j < directions.length - 1; j++) {
int x = cur[0] + directions[j];
int y = cur[1] + directions[j + 1];
if (x < 0 || x >= row || y < 0 || y >= col || image[x][y] != pre) continue;
image[x][y] = newColor;
q.offer(new int[]{x, y});
}
}
}
return image;
}
}