Ir al contenido
Ayotl

← Todos los retos

Intermediate · medium · grid, bfs, multi-source-bfs

Rotting Oranges

El reto

El enunciado va en inglés, igual que en el vídeo.

In a grid, 0 is an empty cell, 1 a fresh orange and 2 a rotten one. Every minute, each rotten orange rots the fresh oranges right next to it: up, down, left and right. Return the number of minutes until no fresh orange is left, or -1 if some of them can never rot.

Example

2 1 1
1 1 0      ->  4
0 1 1

2 1 1
0 1 1      ->  -1   (the orange in the bottom-left corner is cut off)
1 0 1

Idea: a breadth-first search that starts from every rotten orange at the same time (multi-source BFS). The first wave is the oranges that are rotten at minute 0; each wave rots the fresh neighbors of the one before, and those become the next wave. Count the waves while fresh oranges remain; if the waves run out and some orange is still fresh, the answer is -1. Every cell enters the queue at most once: time O(rows x cols).

La solución

# Rotting Oranges - ayotl.dev
def around(r, c):
    return ((r + 1, c), (r - 1, c),
            (r, c + 1), (r, c - 1))


def minutes(grid):
    fresh, rotten = set(), []
    for r, row in enumerate(grid):
        for c, v in enumerate(row):
            if v == 1:
                fresh.add((r, c))
            elif v == 2:
                rotten.append((r, c))
    t = 0
    # BFS minute by minute, starting from
    # all the rotten oranges at once
    while rotten and fresh:
        nxt = []
        for r, c in rotten:
            for p in around(r, c):
                if p in fresh:  # rots now
                    fresh.remove(p)
                    nxt.append(p)
        rotten, t = nxt, t + 1
    return -1 if fresh else t


print(minutes([[2, 1, 1], [1, 1, 0],
               [0, 1, 1]]))
print(minutes([[2, 1, 1], [0, 1, 1],
               [1, 0, 1]]))

$ python3 rotting_oranges.py

4

-1

El vídeo

Ver en YouTube →