要求
给定一个01矩阵 M,找到矩阵中最长的连续1线段。这条线段可以是水平的、垂直的、对角线的或者反对角线的。
示例:
输入:
[[0,1,1,0],
[0,1,1,0],
[0,0,0,1]]
输出: 3
提示: 给定矩阵中的元素数量不会超过 10,000。
核心代码
class Solution:
def longestLine(self, mat: List[List[int]]) -> int:
if not mat or not mat[0]:
return 0
s1,s2 = len(mat),len(mat[0])
ans = 0
# 检测所有水平的
for i1 in range(s1):
now = 0
for i2 in range(s2):
if mat[i1][i2] == 1:
now += 1
ans = max(ans,now)
else:
now = 0
# 检查所有垂直的
for i2 in range(s2):
now = 0
for i1 in range(s1):
if mat[i1][i2] == 1:
now += 1
ans = max(ans, now)
else:
now = 0
# 检查所有对角线的
for i1 in range(s1):
i2 = 0
now = 0
for i3 in range(min(s1 - i1, s2 - i2)):
if mat[i1 + i3][i2 + i3] == 1:
now += 1
ans = max(ans, now)
else:
now = 0
for i2 in range(s2):
i1 = 0
now = 0
for i3 in range(min(s1 - i1, s2 - i2)):
if mat[i1 + i3][i2 + i3] == 1:
now += 1
ans = max(ans, now)
else:
now = 0
# 检查所有反对角线的
for i2 in range(s2):
i1 = 0
now = 0
for i3 in range(min(s1 - i1, i2 + 1)):
if mat[i1 + i3][i2 - i3] == 1:
now += 1
ans = max(ans, now)
else:
now = 0
for i1 in range(s1):
i2 = s2 - 1
now = 0
for i3 in range(min(s1 - i1, i2 + 1)):
if mat[i1 + i3][i2 - i3] == 1:
now += 1
ans = max(ans, now)
else:
now = 0
return ans
解题思路:我们直接双层遍历,分别对横向、纵向、对角线、反对角线的方向进行数据的统计,思路比较简单,代码较为繁琐。