Skip to content

Commit 9f071de

Browse files
authored
Update Rotting Oranges - Leetcode 994.py
1 parent 87711b9 commit 9f071de

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,43 @@
1+
# Code for Bootcamp
2+
class Solution:
3+
from collections import deque
4+
5+
def orangesRotting(self, grid):
6+
# Initialize variables
7+
Minute = 0
8+
Q = deque()
9+
FreshCount = 0
10+
M, N = len(grid), len(grid[0])
11+
12+
# Populate queue with initial rotten oranges and count fresh oranges
13+
for i in range(M):
14+
for j in range(N):
15+
if grid[i][j] == 2:
16+
Q.append((i, j))
17+
elif grid[i][j] == 1:
18+
FreshCount += 1
19+
20+
# Directions for adjacent cells (right, down, left, up)
21+
Directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
22+
23+
# Perform BFS
24+
while Q and FreshCount > 0:
25+
NumRotting = len(Q)
26+
for _ in range(NumRotting):
27+
i, j = Q.popleft()
28+
for r, c in [(i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j)]:
29+
if 0 <= r < M and 0 <= c < N and grid[r][c] == 1:
30+
grid[r][c] = 2
31+
FreshCount -= 1
32+
Q.append((r, c))
33+
Minute += 1 # Increment minute after processing all rotten oranges in this round
34+
35+
# Return the time taken or -1 if fresh oranges remain
36+
return Minute if FreshCount == 0 else -1
37+
38+
39+
40+
# Code for YouTube Video
141
from collections import deque
242
class Solution:
343
def orangesRotting(self, grid: List[List[int]]) -> int:

0 commit comments

Comments
 (0)