| 2 | # Space Complexity = O(rows*columns) |
| 3 | |
| 4 | class Solution: |
| 5 | def orangesRotting(self, grid: List[List[int]]) -> int: |
| 6 | n = len(grid) |
| 7 | m = len(grid[0]) |
| 8 | |
| 9 | count = 0 |
| 10 | rotten = [] |
| 11 | for i in range(n): |
| 12 | for j in range(m): |
| 13 | if grid[i][j]==2: |
| 14 | rotten.append((i,j)) |
| 15 | count+=1 |
| 16 | elif grid[i][j] == 1: |
| 17 | count+=1 |
| 18 | |
| 19 | |
| 20 | if count == 0: |
| 21 | return 0 |
| 22 | |
| 23 | cycles = 0 |
| 24 | |
| 25 | while rotten: |
| 26 | count-=len(rotten) |
| 27 | newRotten = [] |
| 28 | for i,j in rotten: |
| 29 | self.destroy(grid,i+1,j,n,m,newRotten) |
| 30 | self.destroy(grid,i-1,j,n,m,newRotten) |
| 31 | self.destroy(grid,i,j+1,n,m,newRotten) |
| 32 | self.destroy(grid,i,j-1,n,m,newRotten) |
| 33 | rotten = newRotten |
| 34 | cycles+=1 |
| 35 | |
| 36 | if count>0: |
| 37 | return -1 |
| 38 | else: |
| 39 | return cycles-1 |
| 40 | |
| 41 | def destroy(self, grid, i, j, n, m, rotten): |
| 42 | if 0<=i<n and 0<=j<m: |
| 43 | if grid[i][j] == 1: |
| 44 | rotten.append((i,j)) |
| 45 | grid[i][j]=2 |
| 46 | |
| 47 |
nothing calls this directly
no outgoing calls
no test coverage detected