Problem Description
Given an m x n binary matrix, the task is to find the length of the longest line of consecutive 1s in the matrix. The consecutive line may be horizontal, vertical, diagonal, or anti-diagonal.
Key Insights
- The problem involves scanning the matrix in four different directions for each cell that contains a 1.
- Use dynamic programming to store the count of consecutive ones ending at each cell in each direction.
- Update counts based on previously computed adjacent cells, which avoids redundant computations.
- The four directions to consider are:
- Horizontal: left to right
- Vertical: top to bottom
- Diagonal: top-left to bottom-right
- Anti-diagonal: top-right to bottom-left
Space and Time Complexity
Time Complexity: O(m * n) where m and n are the dimensions of the matrix. Space Complexity: O(m * n) if using auxiliary DP arrays for each direction, but can be optimized to O(n) per direction when processing row by row.
Solution
We solve the problem using a dynamic programming approach that maintains four auxiliary arrays (or matrices) for the number of consecutive ones in horizontal, vertical, diagonal, and anti-diagonal directions that end at the current cell. For a cell at position (i, j):
- For the horizontal direction, if the current cell has a 1, add 1 to the count from its left (i, j-1).
- For the vertical direction, add 1 to the count from cell (i-1, j).
- For the diagonal direction, add 1 to the count from the cell (i-1, j-1).
- For the anti-diagonal direction, add 1 to the count from the cell (i-1, j+1). By tracking the maximum value among these counts throughout the matrix traversal, we obtain the answer.