Graph Theory37 sections · 1633 units
Open in Course

LeetCode 994 Rotting Oranges - Implementation

The code

Here's the solution:

function orangesRotting(grid):
    rows := number of rows in grid
    cols := number of columns in grid
    queue := empty queue
    fresh := 0
    minutes := 0
    directions := [(0,1), (1,0), (0,-1), (-1,0)]

    for r from 0 to rows - 1:
        for c from 0 to cols - 1:
            if grid[r][c] = 2 then
                push (r, c) to queue
            else if grid[r][c] = 1 then
                fresh := fresh + 1

    if fresh = 0 then
        return 0

    while queue is not empty:
        size := size of queue
        for i from 0 to size - 1:
            (r, c) := pop from queue
            for each (dr, dc) in directions:
                nr := r + dr
                nc := c + dc
                if nr, nc is in bounds and grid[nr][nc] = 1 then
                    grid[nr][nc] := 2
                    fresh := fresh - 1
                    push (nr, nc) to queue
        minutes := minutes + 1

    if fresh > 0 then
        return -1
    return minutes - 1

Time: O(rows×cols)O(rows \times cols). Space: O(rows×cols)O(rows \times cols) for the queue.