Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created March 13, 2020 05:57
Show Gist options
  • Save RP-3/27cc8fb20a264c3c86b6519cecc591f7 to your computer and use it in GitHub Desktop.
Save RP-3/27cc8fb20a264c3c86b6519cecc591f7 to your computer and use it in GitHub Desktop.
from collections import deque
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q = deque()
seen = set()
maxDay = 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 2:
q.append((row, col, 0))
while(len(q)):
i, j, day = q.popleft()
if (i, j) in seen:
continue
seen.add((i, j))
maxDay = max(maxDay, day)
grid[i][j] = 2
adjacent = [(i+1, j),(i-1, j),(i, j+1),(i, j-1)]
for y, x in adjacent: # for all neighboring fresh oranges
if y>-1 and y<len(grid) and\
x>-1 and x<len(grid[0]) and\
(y, x) not in seen and\
grid[y][x] == 1:
q.append((y, x, day+1)) # add to queue
# check no fresh oranges still exit
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 1:
return -1
return maxDay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment