-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathrotting-oranges.py
241 lines (197 loc) · 7.57 KB
/
rotting-oranges.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""
994. Rotting Oranges
Medium
You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j] is 0, 1, or 2.
"""
# V0
class Solution(object):
def orangesRotting(self, grid):
n = len(grid)
m = len(grid[0])
count = 0
q = []
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
count += 1
elif grid[i][j] == 2:
q.append((i,j,0))
seen = set()
while q:
y, x, d = q.pop(0)
dirs = [(-1, 0), (+1, 0), (0, -1), (0, +1)]
for _dir in dirs:
x1 = x + _dir[0]
y1 = y + _dir[1]
if 0 <= y1 < n and 0 <= x1 < m and (y1, x1) not in seen and grid[y1][x1] == 1:
seen.add((y1,x1))
count -= 1
if count == 0:
return d+1
q.append((y1, x1, d+1))
return 0 if count == 0 else -1
# V1
# IDEA : BFS
# https://leetcode.com/problems/rotting-oranges/discuss/239032/Python-solution
class Solution(object):
def orangesRotting(self, grid):
n = len(grid)
m = len(grid[0])
count = 0
q = collections.deque()
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
count += 1
elif grid[i][j] == 2:
q.append((i,j,0))
seen = set()
while q:
y, x, d = q.popleft()
dirs = {(y-1,x),(y+1,x),(y,x+1),(y,x-1)}
for y1,x1 in dirs:
if 0 <= y1 < n and 0 <= x1 < m and (y1, x1) not in seen and grid[y1][x1] == 1:
seen.add((y1,x1))
count -= 1
if count == 0:
return d+1
q.append((y1, x1, d+1))
return 0 if count == 0 else -1
# V1'
# IDEA : BFS
# https://leetcode.com/problems/rotting-oranges/discuss/781882/Python-by-BFS-%2B-timestamp-w-Demo
from collections import deque
class Solution:
def orangesRotting(self, grid):
# Constant for grid state
VISITED = -1
EMPTY = 0
FRESH = 1
ROTTEN = 2
# Get dimension of grid
h, w = len(grid), len(grid[0])
# record for fresh oranges
fresh_count = 0
# record for position of initial rotten oranges
rotten_grid = []
# board prescan for parameter initialization
for y in range(h):
for x in range(w):
if grid[y][x] == FRESH:
fresh_count += 1
elif grid[y][x] == ROTTEN:
rotten_grid.append( (x, y, 0) )
traversal_queue = deque(rotten_grid)
time_record = 0
# BFS to rotting oranges
while traversal_queue:
x, y, time_stamp = traversal_queue.popleft()
for dx, dy in ( (-1, 0), (+1, 0), (0, -1), (0, +1) ):
next_x, next_y = x + dx, y + dy
if 0 <= next_x < w and 0 <= next_y < h and grid[next_y][next_x] == FRESH:
fresh_count -= 1
grid[next_y][next_x] = VISITED
# update time record
time_record = time_stamp + 1
# adding current rotten orange to traversal queue
traversal_queue.append( (next_x, next_y, time_stamp + 1) )
if fresh_count == 0:
return time_record
else:
return -1
# V1''
# IDEA : BFS
# https://leetcode.com/problems/rotting-oranges/discuss/238862/Python-bfs
class Solution:
def orangesRotting(self, g):
q, good = [], 0
for i, r in enumerate(g):
for j, c in enumerate(r):
if c == 2: q.append((i, j))
elif c == 1: good += 1
total, m, n = 0, len(g), len(g[0])
while q:
nxt_q = []
if good == 0: return total
total += 1
for i, j in q:
for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
if 0 <= x < m and 0 <= y < n and g[x][y] == 1:
g[x][y] = 2
good -= 1
nxt_q.append((x, y))
q = nxt_q
return total if good == 0 else -1
# V1'''
# IDEA : BFS
# https://leetcode.com/problems/rotting-oranges/discuss/388104/Python-10-lines-BFS-beat-97
class Solution:
def orangesRotting(self, grid):
row, col = len(grid), len(grid[0])
rotting = {(i, j) for i in range(row) for j in range(col) if grid[i][j] == 2}
fresh = {(i, j) for i in range(row) for j in range(col) if grid[i][j] == 1}
timer = 0
while fresh:
if not rotting: return -1
rotting = {(i+di, j+dj) for i, j in rotting for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)] if (i+di, j+dj) in fresh}
fresh -= rotting
timer += 1
return timer
# V1''''
# IDEA : DP
# https://leetcode.com/problems/rotting-oranges/discuss/342939/Python-DP-Solution
class Solution:
def orangesRotting(self, grid):
m = len(grid)
n = len(grid[0])
DP = [[[float('inf') for k in range(m*n)] for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
for t in range(m*n):
if grid[i][j] == 2:
DP[i][j][t] = 0
else:
DP[i][j][t] = float('inf')
for t in range(1, m*n):
for i in range(m):
for j in range(n):
if i + 1 < m and grid[i + 1][j] != 0:
DP[i][j][t] = min(DP[i][j][t], 1 + DP[i + 1][j][t - 1])
if i - 1 >= 0 and grid[i - 1][j] != 0:
DP[i][j][t] = min(DP[i][j][t], 1 + DP[i - 1][j][t - 1])
if j + 1 < n and grid[i][j + 1] != 0:
DP[i][j][t] = min(DP[i][j][t], 1 + DP[i][j + 1][t - 1])
if j - 1 >= 0 and grid[i][j - 1] != 0:
DP[i][j][t] = min(DP[i][j][t], 1 + DP[i][j - 1][t - 1])
res = -float('inf')
noOnesFlag = True
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and DP[i][j][m*n - 1] > res:
res = DP[i][j][m*n - 1]
noOnesFlag = False
if noOnesFlag == True:
return 0
return res if res < float('inf') else -1
# V2