Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8ef96d4

Browse files
Merge pull request doocs#235 from phuclhv/master
Add Solution.py for 0994.Rotten Oranges
2 parents 36d078a + 588d91d commit 8ef96d4

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
'''
2+
https://leetcode.com/problems/rotting-oranges/
3+
4+
In a given grid, each cell can have one of three values:
5+
6+
the value 0 representing an empty cell;
7+
the value 1 representing a fresh orange;
8+
the value 2 representing a rotten orange.
9+
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
10+
11+
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
12+
13+
Runtime: 44 ms, faster than 98.53% of Python3 online submissions for Rotting Oranges.
14+
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Rotting Oranges.
15+
'''
16+
17+
from collections import deque
18+
class Solution:
19+
def orangesRotting(self, grid) -> int:
20+
# Setting up common used variable
21+
max_row = len(grid)
22+
max_col = len(grid[0])
23+
rotten_oranges = []
24+
25+
# Put all of initial rottens orange in one array
26+
for row in range(max_row):
27+
for col in range(max_col):
28+
if grid[row][col] == 2:
29+
rotten_oranges.append((row,col))
30+
# Hepler function. If the grid contain fresh orange, it will become rotten
31+
def spread_rotten(row,col):
32+
nonlocal grid, temp_rotten_oranges
33+
if grid[row][col] == 1:
34+
temp_rotten_oranges.append((row,col))
35+
grid[row][col] = 2
36+
37+
# Each loop represent a minutes
38+
# In a loop, we use a temp array to store all of the rotten array got spreaded in that minutes
39+
# The loop only ends when the temp array is empty
40+
time = 0
41+
while True:
42+
temp_rotten_oranges = []
43+
for rotten_orange in rotten_oranges:
44+
row, col = rotten_orange
45+
if row > 0:
46+
spread_rotten(row-1, col)
47+
if col > 0:
48+
spread_rotten(row, col-1)
49+
if row < max_row - 1:
50+
spread_rotten(row+1, col)
51+
if col < max_col - 1:
52+
spread_rotten(row, col+1)
53+
if not temp_rotten_oranges:
54+
break
55+
rotten_oranges = temp_rotten_oranges.copy()
56+
time += 1
57+
58+
# Check the remaing array, return -1 if there's still a fresh orange left
59+
for row in range(max_row):
60+
for col in range(max_col):
61+
if grid[row][col] == 1:
62+
return -1
63+
64+
return time
65+
66+
67+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /