Leetcode 329 Solution

This article provides solution to leetcode question 329 (longest-increasing-path-in-a-matrix)

https://leetcode.com/problems/longest-increasing-path-in-a-matrix

Solution

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix, int m, int n, int i, int j, vector<vector<int>>& cache)
    {
        if (cache[i][j])
            return cache[i][j];

        int res = 1;
        if (i > 0 && matrix[i][j] < matrix[i - 1][j])
            res = max(res, longestIncreasingPath(matrix, m, n, i - 1, j, cache) + 1);

        if (i < m - 1 && matrix[i][j] < matrix[i + 1][j])
            res = max(res, longestIncreasingPath(matrix, m, n, i + 1, j, cache) + 1);

        if (j > 0 && matrix[i][j] < matrix[i][j - 1])
            res = max(res, longestIncreasingPath(matrix, m, n, i, j - 1, cache) + 1);

        if (j < n - 1 && matrix[i][j] < matrix[i][j + 1])
            res = max(res, longestIncreasingPath(matrix, m, n, i, j + 1, cache) + 1);

        return cache[i][j] = res;
    }

    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if (m == 0)
            return 0;
        int n = matrix[0].size();

        vector<vector<int>> cache(m, vector<int>(n, 0));

        int max_path = 0;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int res = longestIncreasingPath(matrix, m, n, i, j, cache);
                max_path = max(res, max_path);
            }
        }

        return max_path;
    }
};