Created
September 29, 2021 22:07
-
-
Save zazaulola/3da4ba250aabe94067ed18d48be1af94 to your computer and use it in GitHub Desktop.
flood-fill algorithm pattern on javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
How does your Image inputs work? My program focuses on ImageData objects, so I want to know what to convert to