LeetCode 994: Rotting Oranges

link

We let rotting wavefronts emanate from all rotten oranges in each iteration of BFS. As soon as fresh orange count drops to zero we are done.

Time: \mathcal{O}(m \cdot n), space: \mathcal{O}(m \cdot n).

from itertools import product as cartesian

class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        def neibors(u):
            nonlocal m, n
            r, c = u
            for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
                r2, c2 = r + dr, c + dc
                if not (0 <= r2 < m) or not (0 <= c2 < n):
                    continue
                if grid[r2][c2] != 1:
                    continue
                yield (r2, c2)

        fresh_count = 0
        q = deque()
        for r, c in cartesian(range(m), range(n)):
            if grid[r][c] == 0:
                continue

            if grid[r][c] == 1:
                fresh_count += 1
            else:
                q.append((r, c))

        minute_count = 0
        while q and fresh_count > 0:
            minute_count += 1

            rotten_count = len(q)
            for _ in range(rotten_count):
                u = q.popleft()
                for v_r, v_c in neibors(u):
                    grid[v_r][v_c] = 2
                    fresh_count -= 1
                    q.append((v_r, v_c))

        return minute_count if fresh_count == 0 else -1

Leave a comment