Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated with an alternative solution #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions 900-1000q/994.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,60 @@ def orangesRotting(self, grid):
if grid[row_index][col_index] == 1:
return -1
return result





'''
Alternative Solution
'''


from collections import deque


class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
queue = deque([])
minutes = 0
found1 = False

for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 2:
queue.append((row, col))
elif grid[row][col] == 1:
found1 = True

if not found1: return 0
if not queue: return -1
queue.append((None, None))

while queue:
row, col = queue.popleft()
if row is None and col is None:
if queue:
queue.append((None, None))
minutes += 1
else:
if row + 1 < len(grid) and grid[row + 1][col] not in [2, 0]:
grid[row + 1][col] = 2
queue.append((row + 1, col))
if row - 1 >= 0 and grid[row - 1][col] not in [2, 0]:
grid[row - 1][col] = 2
queue.append((row - 1, col))
if col + 1 < len(grid[0]) and grid[row][col + 1] not in [2, 0]:
grid[row][col + 1] = 2
queue.append((row, col + 1))
if col - 1 >= 0 and grid[row][col - 1] not in [2, 0]:
grid[row][col - 1] = 2
queue.append((row, col - 1))

for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 1:
return -1

return minutes