Leetcode 329. 矩阵中的最长递增路径

// 超时的代码

class Solution {
public:
    int n,m;
    
    bool check(int x, int y, int x_, int y_, vector<vector<int>>& mat)
    {
        // 条件判断
        if(x_ < 0 || x_ >= n ||  y_ < 0 || y_ >= m)
        {
            return false;
        }
        
        if(mat[x_][y_] > mat[x][y])
            return true; 
        else
            return false;
    }
    
    // 从起点x,y出发最远可以走多少步
    int dfs(int x, int y, vector<vector<int>>& mat)
    {
        int m = 0;
        
        if(check(x, y, x-1, y, mat))
        {
             m = max(m, dfs(x-1, y, mat) + 1);
        }
        if(check(x, y, x+1, y, mat))
        {
             m = max(m, dfs(x+1, y, mat) + 1);
        } 
        if(check(x, y, x, y-1, mat))
        {
             m = max(m, dfs( x, y-1, mat) + 1);
        }
        if(check(x, y, x, y+1, mat))
        {
             m = max(m, dfs(x, y+1, mat) + 1);
        }

        return m;
    }
    
    int longestIncreasingPath(vector<vector<int>>& matrix)
    {
        n = matrix.size();
        if(n==0)
            return 0;
        m = matrix[0].size();
        if(m==0)
            return 0;
        
        //进行穷举计算
        int ans = -1;
        for(int i=0;i<n;++i)
        {
            for(int j=0; j<m; ++j)
            {
                ans = max(ans, dfs(i,j,matrix));
            }
        }
        return ans+1;
    }
};

用深度优先搜索的方式实现代码,结果超时了,有很多冗余的计算在里面,可以使用其他的方法来进行优化。

猜你喜欢

转载自www.cnblogs.com/randyniu/p/9223441.html