马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1, or 2.
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
queue = []
visited = set()
m = len(grid)
n = len(grid[0])
level = 0
count = 0
goal = 0
c = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append([i, j])
visited.add((i, j))
count += 1
goal += 1
if grid[i][j] == 1:
count += 1
c += 1
if c == 0:
return 0
while queue:
size = len(queue)
for i in range(size):
cur = queue.pop(0)
x = cur[0]
y = cur[1]
for direction in directions:
new_x = x + direction[0]
new_y = y + direction[1]
if new_x < 0 or new_x >= m or new_y < 0 or new_y >= n or grid[new_x][new_y] == 0 or (new_x, new_y) in visited:
continue
if grid[new_x][new_y] == 1 and (new_x, new_y) not in visited:
goal += 1
grid[new_x][new_y] = 2
queue.append([new_x, new_y])
visited.add((new_x, new_y))
level += 1
if goal == count:
return level
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
return -1
return level
|