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:
4
💡 Note:
Starting at (0,0) with value 1, go diagonally down-right: 1→2→0→2. This forms a valid V-shaped segment of length 4.
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:
4
💡 Note:
Start at (0,0), go down to (1,0), then turn right to (2,1): 1→2→0→2. V-shape with turn, length 4.
Constraints
- 1 ≤ n, m ≤ 1000
- grid[i][j] ∈ {0, 1, 2}
- At least one element in the grid
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
2D matrix with values 0, 1, 2
2
Pattern Matching
Find segments following 1→2→0→2→0... pattern
3
V-Shape Formation
Allow one clockwise 90° turn to form V-shape
Key Takeaway
🎯 Key Insight: V-shapes are diagonal paths following a specific pattern with at most one clockwise turn
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code