Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Code Block
languagepy
themeEmacs
titleRotting Oranges
linenumberstrue
class Solution:
    def tick(self):
        update_spot = []
        grid = self.grid
        
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                cur = grid[i][j]
                if cur == 2:
                    if i-1 >= 0 and grid[i-1][j] == 1: update_spot.append((i-1, j))
                    if j-1 >= 0 and grid[i][j-1] == 1: update_spot.append((i, j-1))
                    if i+1 < len(grid) and grid[i+1][j] == 1: update_spot.append((i+1, j))
                    if j+1 < len(grid[i]) and grid[i][j+1] == 1: update_spot.append((i, j+1))

        if len(update_spot) == 0:
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == 1:
                        return -1
            return False
        else:
            for spot in update_spot:
                self.grid[spot[0]][spot[1]] = 2

        return True

    def orangesRotting(self, grid: List[List[int]]) -> int:
        self.grid = grid
        count = 0
        while(True):
            res = self.tick()
            if res:
                count = count + 1
            else:
                break

            if res == -1:
                count = -1
                break
            
        return count

...