1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
coloring-a-border.py 1.10 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 6年前 . Create coloring-a-border.py
# Time: O(m * n)
# Space: O(m + n)
import collections
class Solution(object):
def colorBorder(self, grid, r0, c0, color):
"""
:type grid: List[List[int]]
:type r0: int
:type c0: int
:type color: int
:rtype: List[List[int]]
"""
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
lookup, q, borders = set([(r0, c0)]), collections.deque([(r0, c0)]), []
while q:
r, c = q.popleft()
is_border = False
for direction in directions:
nr, nc = r+direction[0], c+direction[1]
if not ((0 <= nr < len(grid)) and \
(0 <= nc < len(grid[0])) and \
grid[nr][nc] == grid[r][c]):
is_border = True
continue
if (nr, nc) in lookup:
continue
lookup.add((nr, nc))
q.append((nr, nc))
if is_border:
borders.append((r, c))
for r, c in borders:
grid[r][c] = color
return grid
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助