classSolution { private: int row_max; int col_max; vector<vector<int>>dp; vector<vector<int>> matrix; // dfs inthelper(int i, int j){ int ans = 0; if (dp[i][j] != 0) { return dp[i][j]; } //up if (i - 1 >= 0 && matrix[i-1][j] > matrix[i][j]) { ans = std::max( ans,helper(i-1, j )+1); } //down if (i + 1 < row_max && matrix[i+1][j ] > matrix[i][j]) { ans = std::max(ans, helper(i+1, j ) + 1); } //left if (j - 1 >= 0 && matrix[i][j - 1] > matrix[i][j]) { ans = std::max(ans, helper(i, j - 1) + 1); } //right if (j + 1 < col_max && matrix[i][j + 1] > matrix[i][j]) { ans = std::max(ans, helper(i, j + 1) + 1); } return dp[i][j] = ans; } public: intlongestIncreasingPath(vector<vector<int>>& matrix){ if (matrix.size() == 0) { return0; } row_max = matrix.size(); col_max = matrix[0].size();
// init the dp array for (int i = 0; i < row_max; i++) { dp.push_back(vector<int>{}); for (int j = 0; j < col_max; j++) { dp[i].push_back(0); } } this->matrix = matrix; int ans = 1 << 31;
// go through each val as head // and finally get the max value. for (int i = 0; i < row_max; i++) { for (int j = 0; j < col_max; j++) { ans = max(ans, helper(i, j) + 1); } } return ans; } };