This problem asks to find the length of the longest line of consecutive 1s in a binary matrix. The line can be horizontal, vertical, diagonal, or anti-diagonal. The most efficient approach is using dynamic programming.
Approach:
The core idea is to use dynamic programming to efficiently track the length of consecutive 1s in each of the four directions (horizontal, vertical, diagonal, and anti-diagonal) for every cell in the matrix. We don't need to explicitly search all possible lines; instead, we build up the solution incrementally.
Initialization: We create four matrices (a
, b
, c
, d
) of the same size as the input matrix, plus padding of one row and one column to simplify boundary handling. These matrices store the lengths of consecutive 1s ending at each cell in the respective directions:
a
: Horizontalb
: Verticalc
: Diagonal (top-left to bottom-right)d
: Anti-diagonal (top-right to bottom-left)Iteration: We iterate through the input matrix. For each cell mat[i][j]
:
mat[i][j] == 1
:
a
, b
, c
, and d
based on the values from the neighboring cells in the respective directions. For example:
a[i][j] = a[i][j-1] + 1
(Horizontal: extend the length from the cell to the left)b[i][j] = b[i-1][j] + 1
(Vertical: extend the length from the cell above)c[i][j] = c[i-1][j-1] + 1
(Diagonal: extend from the top-left)d[i][j] = d[i-1][j+1] + 1
(Anti-diagonal: extend from the top-right)mat[i][j] == 0
: All the values for this cell in the four direction matrices will be 0.Finding the Maximum: After iterating through the entire matrix, we find the maximum value among all the cells in the four DP matrices. This maximum value represents the length of the longest line of consecutive 1s.
Time Complexity: O(M*N), where M and N are the dimensions of the input matrix. We iterate through each cell once.
Space Complexity: O(M*N) because we use four matrices of the same size as the input matrix to store the DP results. While we could potentially optimize the space a bit further, the asymptotic complexity remains the same.
Code Examples:
The provided code snippets in Python, Java, C++, and Go implement this dynamic programming approach. They all follow the same algorithm but have different syntax and data structure implementations. Each language's code accurately reflects the algorithm's steps described above. Note that the use of padding in the DP matrices makes the code simpler by avoiding special handling of boundary conditions.