1034. 边界着色
给你一个大小为 m x n 的整数矩阵 grid ,表示一个网格。另给你三个整数 row、col 和 color 。网格中的每个值表示该位置处的网格块的颜色。
两个网格块属于同一 连通分量 需满足下述全部条件:
两个网格块颜色相同
在上、下、左、右任意一个方向上相邻
连通分量的边界 是指连通分量中满足下述条件之一的所有网格块:
在上、下、左、右任意一个方向上与不属于同一连通分量的网格块相邻
在网格的边界上(第一行/列或最后一行/列)
请你使用指定颜色 color 为所有包含网格块 grid[row][col] 的 连通分量的边界 进行着色,并返回最终的网格 grid 。
示例 1:
输入:grid = [[1,1],[1,2]], row = 0, col = 0, color = 3
输出:[[3,3],[3,2]]
示例 2:
输入:grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3
输出:[[1,3,3],[2,3,3]]
示例 3:
输入:grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2
输出:[[2,2,2],[2,1,2],[2,2,2]]
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j], color <= 1000
0 <= row < m
0 <= col < n
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/coloring-a-border
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
from leetcode_python.utils import *
class Solution:
def __init__(self):
pass
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
self.height,self.width = len(grid), len(grid[0])
self.grid = grid
flag = [[False]*self.width for _ in range(self.height)]
res = [line.copy() for line in grid]
old_color = grid[row][col]
queue = [(row,col)]
flag[row][col]=True
while queue:
row,col = queue.pop(0)
if grid[row][col] == old_color:
for r,c in self.next(row,col):
if not flag[r][c]:
flag[r][c]=True
queue.append((r,c))
if self.isBorder(row,col):
res[row][col]=color
# print('isBorder(1,2)',self.isBorder(1,2))
return res
@lru_cache(None)
def isBorder(self,row,col):
if row in [0,self.height-1] or col in [0,self.width-1]:return True
else:
color = self.grid[row][col]
# print(row,col,color,[self.grid[r][c] for r,c in self.next(row,col)])
return any([self.grid[r][c]!=color for r,c in self.next(row,col)])
@lru_cache(None)
def next(self,rowid,colid):
res = []
for row_id, col_id in ((rowid - 1, colid), (rowid, colid - 1), (rowid + 1, colid), (rowid, colid + 1)):
if 0 <= row_id < self.height and 0 <= col_id < self.width:
res.append([row_id, col_id])
return res
def test(data_test):
s = Solution()
data = data_test # normal
# data = [list2node(data_test[0])] # list转node
return s.colorBorder(*data)
def test_obj(data_test):
result = [None]
obj = Solution(*data_test[1][0])
for fun, data in zip(data_test[0][1::], data_test[1][1::]):
if data:
res = obj.__getattribute__(fun)(*data)
else:
res = obj.__getattribute__(fun)()
result.append(res)
return result
if __name__ == '__main__':
datas = [
# [[[1,2,1],[1,2,2],[2,2,1]],1,1,2],
[[[1,2,2,2,1],[1,2,2,2,1],[1,2,2,2,1],[1,2,2,2,1],[1,2,1,2,1],[1,2,2,2,1],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[1,2,2,2,1],[1,2,1,2,1]],0,1,3],
]
for data_test in datas:
t0 = time.time()
print('-' * 50)
print('input:', data_test)
print('output:', test(data_test))
print(f'use time:{time.time() - t0}s')
备注:
GitHub:https://github.com/monijuan/leetcode_python
CSDN汇总:模拟卷Leetcode 题解汇总_卷子的博客-CSDN博客
可以加QQ群交流:1092754609
leetcode_python.utils详见汇总页说明
先刷的题,之后用脚本生成的blog,如果有错请留言,我看到了会修改的!谢谢!