Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
rotting-oranges.py 993 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-02-17 17:18 +08:00 . Create rotting-oranges.py
# Time: O(m * n)
# Space: O(m * n)
import collections
class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
count = 0
q = collections.deque()
for r, row in enumerate(grid):
for c, val in enumerate(row):
if val == 2:
q.append((r, c, 0))
elif val == 1:
count += 1
result = 0
while q:
r, c, result = q.popleft()
for d in directions:
nr, nc = r+d[0], c+d[1]
if not (0 <= nr < len(grid) and \
0 <= nc < len(grid[r])):
continue
if grid[nr][nc] == 1:
count -= 1
grid[nr][nc] = 2
q.append((nr, nc, result+1))
return result if count == 0 else -1
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助