Skip to content

Instantly share code, notes, and snippets.

@d12
Created January 2, 2022 00:50
Show Gist options
  • Save d12/06fea534b547a468e13c7dcdedc49d8e to your computer and use it in GitHub Desktop.
Save d12/06fea534b547a468e13c7dcdedc49d8e to your computer and use it in GitHub Desktop.
# @param {Integer[][]} image
# @param {Integer} sr
# @param {Integer} sc
# @param {Integer} new_color
# @return {Integer[][]}
def flood_fill(image, sr, sc, new_color)
x_max = image.length - 1
y_max = image[0].length - 1
stack = [[sr, sc]]
visited = {}
flood_value = image[sr][sc]
until stack.empty?
x, y = stack.pop
# Bail if we've visited this node
next if visited[[x,y]]
visited[[x,y]] = true
# Bail if this node isn't the right value
next unless image[x][y] == flood_value
# Set color
image[x][y] = new_color
# Add neighbors to the stack
stack << [x, y + 1] if y < y_max
stack << [x, y - 1] if y > 0
stack << [x + 1, y] if x < x_max
stack << [x - 1, y] if x > 0
end
image
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment