Solution to Leetcode’s Flood Fill

flood fill description

CONCEPT

To get a clearer picture of what the question wants us to do, first, it will be better to break the multidimensional array elements to form a square-like structure e.g the picture below shows the break down of [[1,1,1], [1,1,0], [1,0,1]]:

splitting of array elements
flood fill transition steps
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (image[sr][sc] == newColor) return image;

flood(image, image[sr][sc], newColor, sr, sc);

return image;
}

public void flood(int[][] image, int color, int newColor, int sr, int sc) {
if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length || image[sr][sc] != color) {
return;
}

image[sr][sc] = newColor;

int topRowNeighbour = sr - 1;
int bottomRowNeighbour = sr + 1;
int leftColumnNeigbour = sc - 1;
int rightColumnNeighbour = sc + 1;

flood(image, color, newColor, topRowNeighbour, sc );
flood(image, color, newColor, bottomRowNeighbour, sc );
flood(image, color, newColor, sr, leftColumnNeigbour );
flood(image, color, newColor, sr, rightColumnNeighbour );
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store