|
| 1 | +''' |
| 2 | +In a given grid, each cell can have one of three values: |
| 3 | +
|
| 4 | +the value 0 representing an empty cell; |
| 5 | +the value 1 representing a fresh orange; |
| 6 | +the value 2 representing a rotten orange. |
| 7 | +Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. |
| 8 | +
|
| 9 | +Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. |
| 10 | +''' |
| 11 | + |
| 12 | +class Solution(object): |
| 13 | + def valid(self, row, col, row_size, col_size): |
| 14 | + return row >= 0 and col >= 0 and row < row_size and col < col_size |
| 15 | + |
| 16 | + def orangesRotting(self, grid): |
| 17 | + """ |
| 18 | + :type grid: List[List[int]] |
| 19 | + :rtype: int |
| 20 | + """ |
| 21 | + queue = [] |
| 22 | + for row_index in range(len(grid)): |
| 23 | + for col_index in range(len(grid[0])): |
| 24 | + if grid[row_index][col_index] == 2: |
| 25 | + queue.append((row_index, col_index)) |
| 26 | + |
| 27 | + result = 0 |
| 28 | + queue.append((-1, -1)) |
| 29 | + while queue: |
| 30 | + flag = False |
| 31 | + print queue |
| 32 | + while(queue[0][0] != -1 and queue[0][1] != -1): |
| 33 | + (row, col) = queue[0] |
| 34 | + if self.valid(row+1, col, len(grid), len(grid[0])) and grid[row+1][col] == 1 : |
| 35 | + if not flag: |
| 36 | + result += 1 |
| 37 | + flag =True |
| 38 | + grid[row+1][col] = 2 |
| 39 | + row += 1 |
| 40 | + queue.append((row, col)) |
| 41 | + row -= 1 |
| 42 | + if self.valid(row-1, col, len(grid), len(grid[0])) and grid[row-1][col] == 1 : |
| 43 | + if not flag: |
| 44 | + result += 1 |
| 45 | + flag =True |
| 46 | + grid[row-1][col] = 2 |
| 47 | + row -= 1 |
| 48 | + queue.append((row, col)) |
| 49 | + row += 1 |
| 50 | + if self.valid(row, col+1, len(grid), len(grid[0])) and grid[row][col+1] == 1 : |
| 51 | + if not flag: |
| 52 | + result += 1 |
| 53 | + flag =True |
| 54 | + grid[row][col+1] = 2 |
| 55 | + col += 1 |
| 56 | + queue.append((row, col)) |
| 57 | + col -= 1 |
| 58 | + if self.valid(row, col-1, len(grid), len(grid[0])) and grid[row][col-1] == 1 : |
| 59 | + if not flag: |
| 60 | + result += 1 |
| 61 | + flag =True |
| 62 | + grid[row][col-1] = 2 |
| 63 | + col -= 1 |
| 64 | + queue.append((row, col)) |
| 65 | + col += 1 |
| 66 | + queue.pop(0) |
| 67 | + queue.pop(0) |
| 68 | + if queue: |
| 69 | + queue.append((-1, -1)) |
| 70 | + for row_index in range(len(grid)): |
| 71 | + for col_index in range(len(grid[0])): |
| 72 | + if grid[row_index][col_index] == 1: |
| 73 | + return -1 |
| 74 | + return result |
0 commit comments