aboutsummaryrefslogtreecommitdiff
path: root/longest_increasing_matrix_path.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /longest_increasing_matrix_path.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'longest_increasing_matrix_path.cpp')
-rw-r--r--longest_increasing_matrix_path.cpp32
1 files changed, 32 insertions, 0 deletions
diff --git a/longest_increasing_matrix_path.cpp b/longest_increasing_matrix_path.cpp
new file mode 100644
index 0000000..1ee5b99
--- /dev/null
+++ b/longest_increasing_matrix_path.cpp
@@ -0,0 +1,32 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ int longestIncreasingPath(vector<vector<int>> &matrix) {
+ int rows = matrix.size(), cols = matrix[0].size();
+ if (!rows)
+ return 0;
+ vector<vector<int>> dp(rows, vector<int>(cols, 0));
+ function<int(int, int)> dfs = [&](int x, int y) {
+ if (dp[x][y])
+ return dp[x][y];
+ vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
+ for (auto &dir : dirs) {
+ int x2 = x + dir[0], y2 = y + dir[1];
+ if (x2 < 0 || x2 >= rows || y2 < 0 || y2 >= cols)
+ continue;
+ if (matrix[x2][y2] <= matrix[x][y])
+ continue;
+ dp[x][y] = max(dp[x][y], dfs(x2, y2));
+ }
+ return ++dp[x][y];
+ };
+ int ans = 0;
+ for (int i = 0; i < rows; ++i)
+ for (int j = 0; i < cols; ++j)
+ ans = max(ans, dfs(i, j));
+ return ans;
+ }
+};
+
+int main() {}