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.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
Solutions
Solution 1: Dynamic Programming
Thinking
The longest run of ones may go horizontally, vertically, or on either diagonal. Extending from every start is \(O(mn \cdot (m+n))\).
Four tables store the run ending at \((i,j)\) in each direction, taking the cell above, left, upper-left, or upper-right plus one. Zeros stay zero. A one-cell border avoids bounds checks. Track the global maximum.
We define \(f[i][j][k]\) to represent the length of the longest consecutive \(1\)s ending at \((i, j)\) in direction \(k\). The value range of \(k\) is \(0, 1, 2, 3\), representing horizontal, vertical, diagonal, and anti-diagonal directions, respectively.
We can also use four 2D arrays to represent the length of the longest consecutive \(1\)s in the four directions.
We traverse the matrix, and when we encounter \(1\), we update the value of \(f[i][j][k]\). For each position \((i, j)\), we only need to update the values in its four directions. Then we update the answer.
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\), where \(m\) and \(n\) are the number of rows and columns in the matrix, respectively.