From ff16fed22f52415eb75b749f5d11211d6b6c5ab5 Mon Sep 17 00:00:00 2001 From: Ankit <50232341+imankit007@users.noreply.github.com> Date: Wed, 27 Aug 2025 21:14:27 +0530 Subject: [PATCH] Update 3459.cpp Changes: Change DP state to 4D. Remove variable hashNum in function dfs. Description: The value of grid[i][j] does not need to be included as a DP state variable because it does not change during iteration. This reduction in dimensionality improves space complexity. The existing solution exceeds the time limit on some test cases. --- .../3459.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/solutions/3459. Length of Longest V-Shaped Diagonal Segment/3459.cpp b/solutions/3459. Length of Longest V-Shaped Diagonal Segment/3459.cpp index 3a3e16bf4e0..9e001b624be 100644 --- a/solutions/3459. Length of Longest V-Shaped Diagonal Segment/3459.cpp +++ b/solutions/3459. Length of Longest V-Shaped Diagonal Segment/3459.cpp @@ -3,10 +3,10 @@ class Solution { int lenOfVDiagonal(vector>& grid) { const int m = grid.size(); const int n = grid[0].size(); - vector>>>> mem( - m, vector>>>( - n, vector>>( - 2, vector>(2, vector(4, -1))))); + vector>>> mem( + m, vector>>( + n, vector>( + 2, vector(4, -1)))); int res = 0; for (int i = 0; i < m; ++i) @@ -25,15 +25,14 @@ class Solution { static constexpr int kDirs[4][2] = {{-1, 1}, {1, 1}, {1, -1}, {-1, -1}}; int dfs(const vector>& grid, int i, int j, bool turned, int num, - int dir, vector>>>>& mem) { + int dir, vector>>>& mem) { if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) return 0; if (grid[i][j] != num) return 0; - const int hashNum = max(0, num - 1); - if (mem[i][j][turned][hashNum][dir] != -1) - return mem[i][j][turned][hashNum][dir]; + if (mem[i][j][turned][dir] != -1) + return mem[i][j][turned][dir]; const int nextNum = num == 2 ? 0 : 2; const auto& [dx, dy] = kDirs[dir]; @@ -42,10 +41,10 @@ class Solution { if (!turned) { const int nextDir = (dir + 1) % 4; const auto& [nextDx, nextDy] = kDirs[nextDir]; - res = max(res, 1 + dfs(grid, i + nextDx, j + nextDy, /*turned=*/true, + res = max(res, 1 + dfs(grid, i + nextDx, j + nextDy,/*turned=*/true, nextNum, nextDir, mem)); } - return mem[i][j][turned][hashNum][dir] = res; + return mem[i][j][turned][dir] = res; } };