Approach
Depth-first search
For Length of Longest V-Shaped Diagonal Segment, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 48 lines of Java from the credited upstream file 3459.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int lenOfVDiagonal(int[][] grid) {3 final int m = grid.length;4 final int n = grid[0].length;5 Integer[][][][][] mem = new Integer[m][n][2][2][4];6 7 int ans = 0;8 9 for (int i = 0; i < m; ++i)10 for (int j = 0; j < n; ++j)11 if (grid[i][j] == 1)12 for (int d = 0; d < 4; ++d) {13 final int dx = DIRS[d][0];14 final int dy = DIRS[d][1];15 ans = Math.max(ans, 1 + dfs(grid, i + dx, j + dy, false, 2, d, mem));16 }17 18 return ans;19 }20 21 private static final int[][] DIRS = {{-1, 1}, {1, 1}, {1, -1}, {-1, -1}};22 23 private int dfs(int[][] grid, int i, int j, boolean turned, int num, int dir,24 Integer[][][][][] mem) {25 if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)26 return 0;27 if (grid[i][j] != num)28 return 0;29 30 final int hashNum = Math.max(0, num - 1);31 if (mem[i][j][turned ? 1 : 0][hashNum][dir] != null)32 return mem[i][j][turned ? 1 : 0][hashNum][dir];33 34 final int nextNum = num == 2 ? 0 : 2;35 final int dx = DIRS[dir][0], dy = DIRS[dir][1];36 int res = 1 + dfs(grid, i + dx, j + dy, turned, nextNum, dir, mem);37 38 if (!turned) {39 final int nextDir = (dir + 1) % 4;40 final int nextDx = DIRS[nextDir][0], nextDy = DIRS[nextDir][1];41 res = Math.max(res,42 1 + dfs(grid, i + nextDx, j + nextDy, true, nextNum, nextDir, mem));43 }44 45 return mem[i][j][turned ? 1 : 0][hashNum][dir] = res;46 }47}48