Created
August 10, 2020 05:37
-
-
Save neenjaw/71db39c428c2c6e01477e63c87afd875 to your computer and use it in GitHub Desktop.
Propagating Rotten Oranges
This file contains 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
NOTHING = 0 | |
FRESH_ORANGE = 1 | |
ROTTEN_ORANGE = 2 | |
# @param {Integer[][]} grid | |
# @return {Integer} | |
def oranges_rotting(grid) | |
# Search the grid for rotten oranges | |
next_step = scan_grid(grid, ROTTEN_ORANGE) | |
this_step = [] | |
count = 0 | |
while !next_step.empty? do | |
this_step, next_step = next_step, this_step | |
while !this_step.empty? do | |
y, x = this_step.pop | |
rot_surrounding(grid, y, x, next_step) | |
end | |
count += 1 if !next_step.empty? | |
end | |
scan_grid(grid, FRESH_ORANGE).empty? ? count : -1 | |
end | |
def rot_surrounding(grid, y, x, next_step) | |
height = grid.length | |
width = grid[0].length | |
mutations.each do |(dy, dx)| | |
adj_x = x + dx | |
adj_y = y + dy | |
if (0...height).include?(adj_y) && (0...width).include?(adj_x) && grid[adj_y][adj_x] == FRESH_ORANGE | |
grid[adj_y][adj_x] = ROTTEN_ORANGE | |
next_step.push([adj_y, adj_x]) | |
end | |
end | |
end | |
def mutations | |
[ | |
[-1, 0], | |
[0, -1], | |
[0, 1], | |
[1, 0], | |
] | |
end | |
def scan_grid(grid, type) | |
found = [] | |
grid.each_with_index do |row, y| | |
row.each_with_index do |cell, x| | |
found.push([y, x]) if cell == type | |
end | |
end | |
found | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment