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);
}
}