
Input: mat =[[0,1,1,0],[0,1,1,0],[0,0,0,1]]Output: 3
Example 2:
1
2
3

Input: mat =[[1,1,1,1],[0,1,1,0],[0,0,0,1]]Output: 4
To find the longest line of consecutive ones in all four directions (horizontal, vertical, diagonal, anti-diagonal), we use dynamic programming to keep track of the length of consecutive ones ending at each cell for each direction.
Initialize a 3D dp array where dp[i][j][d] stores the length of consecutive ones ending at cell (i, j) in direction d (0: horizontal, 1: vertical, 2: diagonal, 3: anti-diagonal).
For each cell in the matrix:
If the cell is 1, update dp for all four directions based on previous cells.
classSolution {
funlongestLine(mat: Array<IntArray>): Int {
val m = mat.size
val n = mat[0].size
val dp = Array(m) { Array(n) { IntArray(4) } }
var ans = 0for (i in0 until m) {
for (j in0 until n) {
if (mat[i][j] ==1) {
dp[i][j][0] = if (j > 0) dp[i][j-1][0] + 1else1 dp[i][j][1] = if (i > 0) dp[i-1][j][1] + 1else1 dp[i][j][2] = if (i > 0&& j > 0) dp[i-1][j-1][2] + 1else1 dp[i][j][3] = if (i > 0&& j+1 < n) dp[i-1][j+1][3] + 1else1for (d in0..3) ans = maxOf(ans, dp[i][j][d])
}
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deflongestLine(self, mat: list[list[int]]) -> int:
m, n = len(mat), len(mat[0])
dp = [[[0]*4for _ in range(n)] for _ in range(m)]
ans =0for i in range(m):
for j in range(n):
if mat[i][j] ==1:
dp[i][j][0] = (dp[i][j-1][0] if j >0else0) +1 dp[i][j][1] = (dp[i-1][j][1] if i >0else0) +1 dp[i][j][2] = (dp[i-1][j-1][2] if i >0and j >0else0) +1 dp[i][j][3] = (dp[i-1][j+1][3] if i >0and j+1< n else0) +1 ans = max(ans, dp[i][j][0], dp[i][j][1], dp[i][j][2], dp[i][j][3])
return ans