working solution#625
Conversation
|
Your solution for the "orangesRotting" problem is mostly correct in terms of logic. You have implemented a BFS approach which is suitable for this problem. However, there are a few areas for improvement:
To improve your solution, replace the list with a deque. Also, consider adding comments to explain the steps. Here is a revised version of your code using deque: from collections import deque
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
fresh_count = 0
queue = deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append((i, j))
elif grid[i][j] == 1:
fresh_count += 1
if fresh_count == 0:
return 0
minutes = 0
directions = [(0,1), (1,0), (0,-1), (-1,0)]
while queue:
minutes += 1
for _ in range(len(queue)):
i, j = queue.popleft()
for dx, dy in directions:
r, c = i + dx, j + dy
if 0 <= r < m and 0 <= c < n and grid[r][c] == 1:
grid[r][c] = 2
fresh_count -= 1
queue.append((r, c))
if fresh_count == 0:
return minutes
return -1Note: In this revised code, we increment However, note that the initial rotten oranges are already in the queue. The first iteration of the while loop (with minutes=1) processes these initial rotten oranges. This is correct because the rotting process starts immediately. But wait: if we have initial rotten oranges, they are already rotten at minute 0. Then at minute 1, the oranges adjacent to them become rotten. So the first minute that we count is minute 1. So the code is correct. |
No description provided.