The description of the problem can be found here.
It is a relatively simple problem. To solve this, we can simply use DFS to find all the neighboring tiles with the same color and color them with new color. The code is as follows:
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
// If new color is the same as current color, no change will be made.
if(newColor == image[sr][sc]) return image;
fill(image, sr, sc, image[sr][sc], newColor);
return image;
}
public void fill(int[][] image, int sr, int sc, int color, int newColor){
if(sr < 0 || sr>= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != color) return;
// Don't forget to update the color of the current tile
image[sr][sc] = newColor;
// DFS
fill(image, sr+1, sc, color, newColor);
fill(image, sr-1, sc, color, newColor);
fill(image, sr, sc+1, color, newColor);
fill(image, sr, sc-1, color, newColor);
}
}