Length of Longest V-Shaped Diagonal Segment - Problem
You are given a 2D integer matrix grid of size n x m, where each element is either 0, 1, or 2.
A V-shaped diagonal segment is defined as:
- The segment starts with 1
- The subsequent elements follow this infinite sequence:
2, 0, 2, 0, ... - The segment starts along a diagonal direction (top-left to bottom-right, bottom-right to top-left, top-right to bottom-left, or bottom-left to top-right)
- Continues the sequence in the same diagonal direction
- Makes at most one clockwise 90-degree turn to another diagonal direction while maintaining the sequence
Return the length of the longest V-shaped diagonal segment. If no valid segment exists, return 0.
Input & Output
Example 1 — Basic V-Shape
$
Input:
grid = [[1,2,0],[0,2,0],[1,0,2]]
›
Output:
1
💡 Note:
Starting at (0,0) with value 1, no valid continuation exists following the sequence 1→2→0→2→0... The grid at (1,1) has value 2 but position 2 in sequence expects 0.
Example 2 — No Valid Segment
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]]
›
Output:
1
💡 Note:
Only single cells with value 1 can form segments of length 1, as the sequence 2,0,2,0... cannot be followed.
Example 3 — V-Shape with Turn
$
Input:
grid = [[1,0,0],[2,0,0],[0,2,0]]
›
Output:
1
💡 Note:
Start at (0,0) with value 1. Going down to (1,0) gives value 2, but this is not a diagonal direction. Following diagonal directions, no valid sequence of length > 1 exists.
Constraints
- 1 ≤ n, m ≤ 1000
- grid[i][j] ∈ {0, 1, 2}
- At least one element in the grid
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code