Skip to content

Commit

Permalink
chore: solved rotten oranges question
Browse files Browse the repository at this point in the history
  • Loading branch information
SatyamVyas04 committed Oct 4, 2024
1 parent 9bb7638 commit cc00bb0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 15. Graphs/15.2. BFS-DFS/3. RottenOrangesLeet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import List


class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rotten_positions = []
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 2:
rotten_positions.append((i, j))

directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
minutes = 0

while rotten_positions:
new_rotten_positions = []
for i, j in rotten_positions:
for dx, dy in directions:
x, y = i + dx, j + dy
if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == 1:
grid[x][y] = 2
new_rotten_positions.append((x, y))

rotten_positions = new_rotten_positions
if rotten_positions:
minutes += 1
return -1 if any(1 in row for row in grid) else minutes

0 comments on commit cc00bb0

Please sign in to comment.