https://leetcode.com/contest/weekly-contest-60/problems/flood-fill/
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.
contest60的签到题,题意就是类似各种画图软件里的涂色器功能,把容差内相似的颜色涂成一样的。
名字很直白就是flood fill了,直接就用DFS吧,想象一个铁头娃在挖洞,类似word break那种。与word break不同的是它不需要backtracking的时候恢复现场。
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (image == null || image.length == 0 || sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) {
return image;
}
dfs(image, sr, sc, newColor, new boolean[image.length][image[0].length], image[sr][sc]);
return image;
}
// 111
// 110
// 101
private void dfs(int[][] image, int sr, int sc, int newColor, boolean[][] visited, int originalColor) {
if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length|| visited[sr][sc] || image[sr][sc]!= originalColor) {
return;
}
//铁头娃
image[sr][sc] = newColor;
visited[sr][sc] = true;
dfs(image, sr - 1, sc, newColor, visited, originalColor);
dfs(image, sr + 1, sc, newColor, visited, originalColor);
dfs(image, sr, sc - 1, newColor, visited, originalColor);
dfs(image, sr, sc + 1, newColor, visited, originalColor);
}
}