Leetcode 562 Solution
This article provides solution to leetcode question 562 (longest-line-of-consecutive-one-in-matrix)
Access this page by simply typing in "lcs 562" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix
Solution
class Solution:
def longestLine(self, mat: List[List[int]]) -> int:
m = len(mat)
n = len(mat[0])
dp = [[[0, 0, 0, 0] for _ in range(n)] for _ in range(m)]
ans = 0
for i in range(m):
for j in range(n):
if mat[i][j] == 1:
dp[i][j][0] = 1 + (dp[i][j - 1][0] if j > 0 else 0)
dp[i][j][1] = 1 + (dp[i - 1][j][1] if i > 0 else 0)
dp[i][j][2] = 1 + (dp[i - 1][j - 1][2] if i > 0 and j > 0 else 0)
dp[i][j][3] = 1 + (dp[i - 1][j + 1][3] if i > 0 and j + 1 < n else 0)
else:
dp[i][j][0] = 0
dp[i][j][1] = 0
dp[i][j][2] = 0
dp[i][j][3] = 0
ans = max(ans, max(dp[i][j]))
return ans