2024每日刷题(165)
Leetcode—329. 矩阵中的最长递增路径
dfs + dp实现代码
class Solution {
public:int longestIncreasingPath(vector<vector<int>>& matrix) {// 9 9 4// 6 6 8// 2 1 1// 1 1 2// 2 2 1// 3 4 2int m = matrix.size();int n = matrix[0].size();vector<vector<int>> memo(m, vector<int>(n, 0));function<int(int, int, int)> dfs = [&](int i, int j, int pre) -> int {// out of boundaryif(i < 0 || i == m || j < 0 || j == n) {return 0;}const int cur = matrix[i][j];if(cur <= pre) {return 0;}int &ans = memo[i][j];if(ans > 0) {return ans;}ans = 1 + max({dfs(i, j + 1, cur), dfs(i, j - 1, cur), dfs(i + 1, j, cur), dfs(i - 1, j, cur)});return ans;};int ans = 0;for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {ans = max(ans, dfs(i, j, -1));}}return ans;}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!