From 3742f30fdcca43127b8dee71ea0289cb0041b6ec Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Fri, 20 May 2022 16:40:49 +0800 Subject: [PATCH] add: 220519 [cpp] --- cpp/2205/220519.cpp | 48 +++++++++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220519.cpp diff --git a/cpp/2205/220519.cpp b/cpp/2205/220519.cpp new file mode 100644 index 0000000..1f2c0d0 --- /dev/null +++ b/cpp/2205/220519.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +/** + * 329. Longest Increasing Path in a Matrix + * Given an m x n integers matrix, return the length of the longest increasing path in matrix. + * From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). + */ + +class Solution { +private: + inline static int dX[] = {0, 1, 0, -1}; + inline static int dY[] = {1, 0, -1, 0}; + +public: + static int longestIncreasingPath(const std::vector>& matrix) { + const int m = matrix.size(), n = matrix.front().size(); + + int* dp = new int[m * n]{}; + std::function d = [&](int id) { + if (dp[id]) + return dp[id]; + + const int x = id / n, y = id % n; + // 4 directions + int ans = 1; + for (int i = 0; i < 4; ++i) { + if (x + dX[i] < 0 || x + dX[i] >= m || y + dY[i] < 0 || y + dY[i] >= n || matrix[x + dX[i]][y + dY[i]] <= matrix[x][y]) + continue; + ans = std::max(ans, 1 + d((x + dX[i]) * n + (y + dY[i]))); + } + return dp[id] = ans; + }; + + int ret = 0; + for (int i = 0; i < m * n; ++i) + ret = std::max(ret, d(i)); + + delete[] dp; + return ret; + } +}; + +int main() { + std::printf("%d\n", Solution::longestIncreasingPath({{9,9,4},{6,6,8},{2,1,1}})); + return 0; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index cf2b7cd..365f717 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220519-CN.cpp) +ADD_EXECUTABLE(2205 220519.cpp)