An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, “flood fill” the image.
To perform a “flood fill”, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
给出一个图像(二维数组),给一个起点,从起点开始遍历它的上下左右四邻域,和起点相同颜色的渲染成新的颜色,并继续遍历上下左右,直至遇到和起点不同颜色时停止。
思路:
从起点开始进行一次DFS
要用一个visited数组记录下访问过的位置,而不能用颜色是否更新来判断,因为可能新的颜色和刚开始的颜色是一样的,无法判断是否已访问过,会爆掉
class Solution {
int rows = 0;
int cols = 0;
int initialColor = 0;
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
rows = image.length;
cols = image[0].length;
boolean[][] visited = new boolean[rows][cols];
initialColor = image[sr][sc];
dfs(image, sr, sc, newColor, visited);
return image;
}
void dfs(int[][] image, int sr, int sc, int newColor, boolean[][] visited) {
if(sr < 0 || sr >= rows || sc < 0 || sc >= cols) return;
if(visited[sr][sc]) return;
visited[sr][sc] = true;
if(image[sr][sc] == initialColor) {
image[sr][sc] = newColor;
dfs(image, sr-1, sc, newColor, visited);
dfs(image, sr, sc+1, newColor, visited);
dfs(image, sr+1, sc, newColor, visited);
dfs(image, sr, sc-1, newColor, visited);
}
//visited[sr][sc] = false;
}
}
还有一种方法是一开始就判断新颜色是否和起点颜色相同,相同的话就直接返回,这样就可以不用visited数组。
class Solution {
int rows = 0;
int cols = 0;
int initialColor = 0;
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
rows = image.length;
cols = image[0].length;
initialColor = image[sr][sc];
if(initialColor != newColor) dfs(image, sr, sc, newColor);
return image;
}
void dfs(int[][] image, int sr, int sc, int newColor) {
if(sr < 0 || sr >= rows || sc < 0 || sc >= cols) return;
if(image[sr][sc] != initialColor) return;
image[sr][sc] = newColor;
dfs(image, sr-1, sc, newColor);
dfs(image, sr, sc+1, newColor);
dfs(image, sr+1, sc, newColor);
dfs(image, sr, sc-1, newColor);
}
}
博客围绕图像填充问题展开,给出一个二维数组表示的图像、起点和新颜色,需将与起点同色且四邻域相连的像素渲染为新颜色。介绍了使用深度优先搜索(DFS)解决该问题,可使用visited数组记录访问位置,也可先判断新颜色与起点颜色是否相同,相同则直接返回。
422

被折叠的 条评论
为什么被折叠?



