Longest Border-Ending Diagonal Pattern
Problem statement
Given a rectangular integer matrix matrix, find the longest diagonal segment that matches the infinite pattern 1, 2, 0, 2, 0, ....
A valid segment:
- starts at any matrix cell whose value is
1; - continues in exactly one of the four diagonal directions;
- matches
2after the initial1, then alternates0and2; and - ends at a cell on the first row, last row, first column, or last column.
Return the maximum length of a valid segment.
Function
longestBorderDiagonal(matrix: int[][]) → intExamples
Example 1
matrix = [[0,0,1,2],[0,2,2,2],[2,1,0,1]]return = 3Starting at matrix[2][3] and moving up-left produces 1, 2, 0 at cells (2,3), (1,2), and (0,1). The last cell is on the first row, so this is a valid length-3 segment. No longer valid segment exists.
Constraints
matrixis non-empty and rectangular.- Every matrix value is
0,1, or2. - A segment moves by one row and one column at each step and never changes direction.
- A solution with time complexity no worse than
O(matrix.length^2 * matrix[0].length^2)fits the source's execution limit.