An
Given a coordinate
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:
Note:
Solution
We can solve it using BFS traversal, take
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
public class FloodFill { int[] a = { 0, -1, 0, 1 }; int[] b = { 1, 0, -1, 0 }; public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int l = image.length; if (l == 0 || newColor == image[sr][sc]) // return if old and new color is same. return image; int m = image[0].length; floodImage(image, sr, sc, l, m, newColor, image[sr][sc]); return image; } public void floodImage(int[][] image, int i, int j, int l, int m, int newClr, int oldClr) { if (i < 0 || j < 0 || i >= l || j >= m) return; if (image[i][j] == oldClr) { image[i][j] = newClr; for (int k = 0; k < 4; k++) { floodImage(image, i + a[k], j + b[k], l, m, newClr, oldClr); } } } private void printImage(int[][] image) { for (int[] row : image) { for (int col : row) { System.out.print(col + " "); } System.out.println(); } } public static void main(String[] args) { int[][] image = { { 1, 1, 1 }, { 1, 1, 0 }, { 1, 0, 1 } }; int sr = 1, sc = 1, newColor = 2; FloodFill floodFillObj = new FloodFill(); floodFillObj.floodFill(image, sr, sc, newColor); floodFillObj.printImage(image); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.
Little smaller version :p
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
DFS(image, sr, sc, image[sr][sc], newColor);
return image;
}
private void DFS(int [][] image, int sr, int sc, int sourceColor, int newColor) {
if (sr image.length-1 || sc image[0].length-1) return;
if (image[sr][sc] != sourceColor) return;
if (image[sr][sc] == newColor) return;
image[sr][sc] = newColor;
DFS(image, sr+1, sc, sourceColor, newColor);
DFS(image, sr-1, sc, sourceColor, newColor);
DFS(image, sr, sc+1, sourceColor, newColor);
DFS(image, sr, sc-1, sourceColor, newColor);
}
}