public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
if (image[sr][sc] != newColor) {
floodFillByDFS(image, sr, sc, image[sr][sc], newColor, directions);
public void floodFillByDFS(int[][] image, int row, int col, int color, int newColor, int[][] directions) {
image[row][col] = newColor;
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (isValid(image, nextRow, nextCol, color)) {
floodFillByDFS(image, nextRow, nextCol, color, newColor, directions);
public boolean isValid(int[][] image, int row, int col, int color) {
return row >= 0 && row < image.length && col >= 0 && col < image[0].length && image[row][col] == color;