Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Created September 29, 2021 22:07
Show Gist options
  • Save zazaulola/3da4ba250aabe94067ed18d48be1af94 to your computer and use it in GitHub Desktop.
Save zazaulola/3da4ba250aabe94067ed18d48be1af94 to your computer and use it in GitHub Desktop.
flood-fill algorithm pattern on javascript
function floodFill(image, sr, sc, newColor) {
const current = image[sr][sc];
if (current != newColor) {
fill(image, sr, sc, newColor, current);
}
return image;
function fill(image, sr, sc, newColor, current) {
if (
sr < 0 ||
sc > 0 ||
sr > image.length - 1 ||
sc > image[sr].length - 1 ||
image[sr][sc] !== current
) {
return;
}
image[sr][sc] = newColor;
fill(image, sr - 1, sc, newColor, current);
fill(image, sr + 1, sc, newColor, current);
fill(image, sr, sc - 1, newColor, current);
fill(image, sr, sc + 1, newColor, current);
}
}
@TheTrueFax
Copy link

How does your Image inputs work? My program focuses on ImageData objects, so I want to know what to convert to

@zazaulola
Copy link
Author

How does your Image inputs work? My program focuses on ImageData objects, so I want to know what to convert to

in this function the image argument is a two-dimensional array in which colors can be represented by any type (either numbers or strings), that is, if they can be checked for equality or inequality, the function will work.

ImageData is a one-dimensional clamped byte array, where each pixel is 4 bytes (r,g,b,a)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment