|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +In a given grid, each cell can have one of three values: |
| 4 | +
|
| 5 | +the value 0 representing an empty cell; |
| 6 | +the value 1 representing a fresh orange; |
| 7 | +the value 2 representing a rotten orange. |
| 8 | +Every minute, any fresh orange that is adjacent (4-directionally) to a rotten |
| 9 | +orange becomes rotten. |
| 10 | +
|
| 11 | +Return the minimum number of minutes that must elapse until no cell has a fresh |
| 12 | +orange. If this is impossible, return -1 instead. |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +
|
| 16 | +Input: [[2,1,1],[1,1,0],[0,1,1]] |
| 17 | +Output: 4 |
| 18 | +Example 2: |
| 19 | +
|
| 20 | +Input: [[2,1,1],[0,1,1],[1,0,1]] |
| 21 | +Output: -1 |
| 22 | +Explanation: The orange in the bottom left corner (row 2, column 0) is never |
| 23 | +rotten, because rotting only happens 4-directionally. |
| 24 | +Example 3: |
| 25 | +
|
| 26 | +Input: [[0,2]] |
| 27 | +Output: 0 |
| 28 | +Explanation: Since there are already no fresh oranges at minute 0, the answer |
| 29 | +is just 0. |
| 30 | +
|
| 31 | +Note: |
| 32 | +1 <= grid.length <= 10 |
| 33 | +1 <= grid[0].length <= 10 |
| 34 | +grid[i][j] is only 0, 1, or 2. |
| 35 | +""" |
| 36 | +from typing import List |
| 37 | + |
| 38 | + |
| 39 | +dirs = ((0, -1), (0, 1), (-1, 0), (1, 0)) |
| 40 | + |
| 41 | + |
| 42 | +class Solution: |
| 43 | + def orangesRotting(self, grid: List[List[int]]) -> int: |
| 44 | + """ |
| 45 | + maintain a q for the newly rotten |
| 46 | + """ |
| 47 | + m, n = len(grid), len(grid[0]) |
| 48 | + q = [] |
| 49 | + for i in range(m): |
| 50 | + for j in range(n): |
| 51 | + if grid[i][j] == 2: |
| 52 | + q.append((i, j)) |
| 53 | + |
| 54 | + t = -1 |
| 55 | + while q: |
| 56 | + t += 1 |
| 57 | + cur_q = [] |
| 58 | + for i, j in q: |
| 59 | + for di, dj in dirs: |
| 60 | + I = i + di |
| 61 | + J = j + dj |
| 62 | + if 0 <= I < m and 0 <= J < n and grid[I][J] == 1: |
| 63 | + grid[I][J] = 2 |
| 64 | + cur_q.append((I, J)) |
| 65 | + q = cur_q |
| 66 | + |
| 67 | + has_fresh = any( |
| 68 | + grid[i][j] == 1 |
| 69 | + for i in range(m) |
| 70 | + for j in range(n) |
| 71 | + ) |
| 72 | + |
| 73 | + return max(0, t) if not has_fresh else -1 |
0 commit comments