From d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa Mon Sep 17 00:00:00 2001 From: jack <0x6A73@pm.me> Date: Fri, 14 Jun 2024 13:13:15 -0600 Subject: initial --- longest_increasing_matrix_path.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 longest_increasing_matrix_path.cpp (limited to 'longest_increasing_matrix_path.cpp') 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> &matrix) { + int rows = matrix.size(), cols = matrix[0].size(); + if (!rows) + return 0; + vector> dp(rows, vector(cols, 0)); + function dfs = [&](int x, int y) { + if (dp[x][y]) + return dp[x][y]; + vector> 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() {} -- cgit v1.2.3