code in java
class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int startColor = image[sr][sc]; if (startColor == newColor) { return image; } fill(image, sr, sc, startColor, newColor); return image; } private void fill(int[][] image, int sr, int sc, int startColor, int newColor) { if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != startColor) { return; } image[sr][sc] = newColor; fill(image, sr - 1, sc, startColor, newColor); fill(image, sr + 1, sc, startColor, newColor); fill(image, sr, sc - 1, startColor, newColor); fill(image, sr, sc + 1, startColor, newColor); } public static void main(String[] args) { Solution solution = new Solution(); int[][] image = { {1, 1, 1}, {1, 1, 0}, {1, 0, 1} }; int sr = 1, sc = 1, newColor = 2; int[][] result = solution.floodFill(image, sr, sc, newColor); System.out.println("Flood-filled image:"); for (int[] row : result) { for (int pixel : row) { System.out.print(pixel + " "); } System.out.println(); } } }