Longest Line of Consecutive One in Matrix Problem
Description
LeetCode Problem 562.
Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.
The line could be horizontal, vertical, diagonal, or anti-diagonal.
Example 1:

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

Input: mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
Output: 4
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 10^41 <= m * n <= 10^4mat[i][j]is either0or1.
Solution
Approach: Dynamic Programming in Four Directions
Starting a walk from every cell in every direction would revisit the same ones many times. Instead, for each cell we ask: how long is the run of ones that ends here, in each of the four directions?
If mat[i][j] is 0, every run ending there has length 0. If it is 1, the run in a direction is one longer than the run ending at the previous cell in that direction:
- horizontal: the cell to the left,
(i, j - 1) - vertical: the cell above,
(i - 1, j) - diagonal: the cell up and to the left,
(i - 1, j - 1) - anti-diagonal: the cell up and to the right,
(i - 1, j + 1)
All four of those cells come earlier in a row-by-row, left-to-right scan, so their values are ready when we need them. The answer is the largest value seen in any table.
The anti-diagonal is the one that looks forward in the column (j + 1), so the tables get a column of padding on both sides, plus a row on top. The padding cells are 0, which means no special case at the borders.
Complexity: O(m·n) time and O(m·n) extra space for the four tables (keeping only the previous row would bring this down to O(n)).
class Solution:
def longestLine(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
# Run of ones ending at each cell, per direction. A border of zeros avoids bounds checks.
hor = [[0] * (n + 2) for _ in range(m + 1)]
ver = [[0] * (n + 2) for _ in range(m + 1)]
diag = [[0] * (n + 2) for _ in range(m + 1)]
anti = [[0] * (n + 2) for _ in range(m + 1)]
ans = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if mat[i - 1][j - 1]:
hor[i][j] = hor[i][j - 1] + 1
ver[i][j] = ver[i - 1][j] + 1
diag[i][j] = diag[i - 1][j - 1] + 1
anti[i][j] = anti[i - 1][j + 1] + 1
ans = max(ans, hor[i][j], ver[i][j], diag[i][j], anti[i][j])
return ans