zoukankan      html  css  js  c++  java
  • 30 Day Challenge Day 15 | Leetcode 329. Longest Increasing Path in a Matrix

    题解

    Hard

    方法一:DFS + Memoization

    class Solution {
    public:
        int longestIncreasingPath(vector<vector<int>>& matrix) {
            if(matrix.empty()) return 0;
    
            m = matrix.size(), n = matrix[0].size();
            
            vector<vector<int>> cache(m, vector<int>(n, 0));
            
            int res = 1;
            
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    res = max(res, dfs(matrix, i, j, cache));
                }
            }
            
            return res;
        }
        
        int dfs(vector<vector<int>>& matrix, int x, int y, vector<vector<int>>& cache) {
            if(cache[x][y] != 0) return cache[x][y];
            
            cache[x][y] = 1;
    
            for(int i = 0; i < 4; i++) {
                int new_x = x + dirs[i][0];
                int new_y = y + dirs[i][1];
                if(new_x >= 0 && new_x < m && new_y >= 0 && new_y < n
                  && matrix[new_x][new_y] > matrix[x][y]) {
                    cache[x][y] = max(cache[x][y], dfs(matrix, new_x, new_y, cache) + 1);
                }
            }
            
            return cache[x][y];
        }
        
    private:
        int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int m, n;
    };
    
  • 相关阅读:
    MQTT
    群晖搭建webssh
    OSI 协议
    centos7 yum安装ffmpeg,以及ffmpeg的简单用法
    centos7 RTMP直播服务器搭建
    elasticsearch
    H5的storage
    bootstrap 列表組
    eclipse的debug模式下启动不了tomcat
    bootstrap collapse
  • 原文地址:https://www.cnblogs.com/casperwin/p/13754376.html
Copyright © 2011-2022 走看看